What Is Belongs To Relationships In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.Today we are going to discuss how can we use Belongs To Relationships in laravel and for what we use Belongs To Relationships in laravel with example

What Is Belongs To Relationships In Laravel With Example

Belongs To Relationships

 A belongsTo() relationship matches a related table's 'id' to a 'localKey' field on 'this' model. Another way to think about it is the belongsTo() relationship should live on the model that has the field that links to the related tables id.

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

 

public function index()
{
    $BankAccount = App\BankAccount::find(10);
    
    $user->BankAccount()->associate($account);
    
    $user->save();
}
 

When removing a belongsTo relationship, you may use the dissociate method. This method will set the relationship's foreign key to null:

public function index()
{

    $BankAccount = App\BankAccount::find(10);

    $user->BankAccount()->dissociate();
    
    $user->save();
}
 


Default Models

The belongsTohasOnehasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\User model if no user is attached to the post:
 

public function user()
{
    return $this->belongsTo('App\User')->withDefault();
}
 

To populate the default model with attributes, you may pass an array or Closure to the withDefault method:
 

/**
* Get the author of the post.
*/
public function user()
{
    return $this->belongsTo('App\User')->withDefault([
    'name' => 'Guest Author',
    ]);
}

/**
* Get the author of the post.
*/
public function user()
{
    return $this->belongsTo('App\User')->withDefault(function ($user, $post) {
    $user->name = 'Guest Author';
});
}

Related Post