Eloquent Relationships Tips Laravel

Eloquent Relationships Tips Laravel

In this article, I'm going to share with you some tips that may help you.

  • Load Only the Columns You Need with Eager Loading
$products = Product::with('categories:id,name')->get();
  • Load Nested Relationship

Image this scenario: The user belongs to a country and this country has a city, meaning we have 3 tables related to each other. How we can access the city from user model?.

$users = User::with('country.city')->get();
  • Default Model

Sometimes you want to access a property from a relationship but this field can be null, for example {{$product->brand->name}}, if the name is null you receive a fatal error, to prevent that use default.

public function brand()
{
    return $this->belongsTo(Brand::class)->withDefault();
}
  • OrderBy

You can order your relationship by the field you need, for example

public function employees()
{
  return $this->hasMany(Employee::class);
}

//Order By
public function employees()
{
  return $this->hasMany(Employee::class)->orderBy('last_name');
}
  • Extra Fields in Pivot Table

In many to many relationships, we can define extra fields in the intermediate table like this

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class)->withPivot('active');
    }
}
  • Rename Pivot Table

Sometimes you want to customize the name of your intermediate table, you can do it using as.

public function podcasts()
{
   return $this->belongsToMany(Podcast::class)
                ->as('subscription')
                ->withTimestamps();
}
  • Filter Relationship

You can use where to filter a relationship


public function active_users()
{
   return $this->hasMany(User::class)->where('active', 1);
}
  • whereRelation

From Laravel 8.57 we can use whereRelation, we can consider an improved version of whereHas

whereHas Example

$products = Product::whereHas('reviews', function ($query) {
    $query->where('stars', '>', 3);
})->get();

whereRelation Example

$products = Product::whereRelation('reviews', 'stars', '>', 3)->get();

If you have more tips leave them in the comment section to update the article.

Thanks for reading.