Backend Development

Using Default Models in Laravel By Using withDefault

Using Default Models in Laravel By Using withDefault

In the latest versions of Laravel framework a new important method add in eloquent models which is the withDefault() method.

 

 

Laravel always makes the development process easy through the features it offers in each release. One of these features is the default models when creating relationships between tables.

To create a default model laravel offers the withDefault() method when creating relationships. The withDefault() can be used with these relationships belongsTo, hasOne, hasOneThrough, and morphOne.

The real benefit is to allow us to define a default model that will be returned if the given relationship is null. As per laravel docs this method uses the Null Object pattern and can help remove conditional checks in your code.

Let’s clarify with an example:

If we have a Product model that have a relation with a User model, so every post belongs to one user:

class Product extends Model
{

   public function user()
   {
       return $this->belongsTo(User::class);
   }

}

Now in your controller you can query for the product owner like so:

$product = Product->find(2);
$owner = $product->user;

If for example the product you want to find not attached to any user i.e the user_id is null in this case the $owner will be null:

$product = Product::find(2222222);
$owner = $product->user;    // null

if($owner) {
  return $owner->name;
} else {
  return "Annonymous";
}

As you see to return the real user you have to make an if statement check for the $owner variable to be sure it’s not null.

Now to make this more clean and instead of making these checks we can utilize the withDefault() method like so:

public function user() 
{ 
    return $this->belongsTo(User::class)->withDefault([
        'name' => 'Annonymous',
    ]);
}

Now your controller code can be simplified like so:

$owner = $product->user; 

return $owner->name; // if user not null then it will display the real name otherwise it will display "Annonymous"

In the above code withDefault() accept an array but it can also accept a closure:

return $this->belongsTo(User::class)->withDefault(function ($user, $product) {
        $user->name = 'Annonymous';
});

You can specify any default fields you want:

public function user() 
{ 
    return $this->belongsTo(User::class)->withDefault([ 
               'name' => 'Annonymous',
               'age' => 'undetermined',
               'school' => 'undetermined',
               'address' => 'undetermined'
    ]); 
}

 

0 0 votes
Article Rating

What's your reaction?

Excited
1
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments