Laravel for accessing relationships - check if data exists from model

Let's say I have a model User

and Group

that has a one-to-many relationship. The user can belong to a group 0

or 1

. A group can have many users.

When I display a list of users, I also want to display his group name - if it belongs to one. So I do this:

$user->group()->first()->name

      

If the user does not belong to the group, this will of course result in an error.

So, I am doing something like this:

!empty($user->group) ? $user->group()->first()->name : 'No group here'

      

Now my application really has more than just Group

. There are many more relationships out there that I look at from inside the show. For example, role, account, etc.

So I really don't want to clutter my opinion with this. Is there a way to check if the data from the model exists?

Something like this, perhaps?

class User extends Model
{
    // .. snip

    public function group()
    {
        if (empty($this->group)) {
            return 'Nothing here';
        }

        return $this->hasOne(App\Group::class);
    }
}

      

Am I wrong? Is it already available? I haven't seen anything in the docs or on google that can help me with this (maybe looking for the wrong words?).

So, if anyone can point me in the right direction, that would be great.

+3


source to share


1 answer


You can create an accessor method in your model User

, for example:

public function getGroupNameAttribute()
{
    $this->group ? $this->group->name : 'Oops! Nothing.';
}

      

So, in the view, you can use something like this:



{{ $user->group_name }}

      

The output will be either the group name or Oops! Nothing.

.

+1


source







All Articles