user5140488
user5140488

Reputation: 83

Get relationship if the row exists

I have two tables, users and roles, where each user can (but doesn't have to) have a role. The relationship exists through role_id and id from the two tables, respectively.

How can I create an Eloquent query that gets the user's role if the row exists?

Here is my current query (although it doesn't do what I need):

$user = User::where('username', 'LIKE', '%abc%')
    ->get();

Upvotes: 1

Views: 51

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

First of all, you need to define a user->role relation in your User model:

public function role() {
  return $this->belongsTo(Role::class);
}

Then you'll be able to load users together with their roles:

$users = User::with('role')->where('username', 'LIKE', '%abc%')->get();

Fetched users should have their role available in

$user->role

If they have no role, the value of this attribute will be NULL

Upvotes: 1

Related Questions