How to use conditions in Laravel Eloquent

Categorized as Laravel

Eloquent is a brilliant ORM – you can use conditions in relationships.

In this example, we have multiple users. In the next step, we set a relationship called admins which extends the user relation with a condition. So easy!

class Team extends Model 
  public function users()
    return $this->hasMany(User::class);

  public function admins()
    return $this->user()->where('role', 'admin');


But you have to be mindful when creating a user via admins relationship. You will need to define the column still. For example, create (['role' => 'admin']) as the builder might not be aware of inserts/updates in that manner. (Sometimes your IDE will know about it and will help you.)

What is Eloquent in Laravel?

Eloquent is an object-relational mapper (ORM) for the Laravel framework. It provides a simple, expressive API for working with your database using PHP. For example, Eloquent makes it easy to map your models to tables in the database and write queries to retrieve data from there. It also provides many convenient methods for performing CRUD operations (create, read, update, delete).

Via @ecrmnn

Leave a reply

Your email address will not be published. Required fields are marked *