0

Im wondering if I could get some advice.

In my blade template, i have the following;

<a href="#">{{ $gallery->creator->name }}</a>

My controller looks like this;

public function show(Gallery $gallery)
{
    return view('galleries.show', compact('gallery'));
}

The next bit is where im having some trouble, In my model i have the following relationship

public function creator()
{
    return $this->belongsTo(User::class, 'user_id');
}

Some of the galleries have a null user_id value as they are not logged in when posted.

Is there a way that I can set the $gallery->creator->name to 'Anonymous' if the user_id is null, but if there is a value, use whats already there? Any help making a mutator would be awesome

Any help would be greatly appreciated.

Cheers,

2
  • you can use a mutator for this, take a look here: laravel mutators Commented Aug 12, 2017 at 2:12
  • @user3681740 Hey, this looks like a good idea ... Is there any chance you could give me an example? Commented Aug 12, 2017 at 2:55

2 Answers 2

1

This is how I fixed this issue in my case.

Inside the Gallery model, where you have this relationship defined:

public function creator()
{
    return $this->belongsTo(User::class, 'user_id');
}

Add this accessor:

public function getCreatorNameAttribute()
{
    if ($this->creator) {
        return $this->creator->name;
    }
    return "Anonymous"; // any default value you want to return here.
}

And how to use it blade template:

<a href="#">{{ $gallery->creatorName }}</a>
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect ... Exactly what i was looking for. Thank you!
Glad, it helps.
0
<a href="#">{{ $gallery->creator ? $gallery->creator->name : 'Anonymous' }}</a>

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.