3

Let's say I have a User and Group model that has a one-to-many relation. User can belong 0 or 1 group. Group can have many users.

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

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

If the user doesn't belong to a group, this will--of course--throw an error.

So I do something like this:

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

Now in my actual app there isn't just group. There a lot more relationships that I loop through from within the view. Like, role, account, etc.

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

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 going about this the wrong way? Is this already available? I haven't seen anything on the docs or on google that can help me with this (maybe looking for the googling the wrong words?).

So if anyone could point me in the right direction, that'd be great.

3
  • This is what you're looking for: stackoverflow.com/a/23911985/784588 And, no, you can't define relationship like that, bc (eager) loading of the relationship won't work. Also, don't use $user->group()->first() but $user->group Commented Jul 10, 2015 at 21:13
  • there is a method FindOrFail() ,check that out Commented Jul 10, 2015 at 21:27
  • So I guess, what you're saying is that's pretty much impossible? So how do you do it instead? The best I could come up with was a ternary expression. $user->group ? $user->group->name : 'No group here'. Commented Jul 10, 2015 at 21:42

1 Answer 1

1

You may create an accessor method in your User model 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 a group name or Oops! Nothing..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.