Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mcbates's avatar

More elegant way to only pass variable if related data in pivot

I want to show related data on a view. It's a company that has branches (in a pivot table). If a company has branches (\App\User::find($id)->branches()I want to pass these branches to the view. If there are no branches, I want to skip the variable.

Here's how I solved it so far. Is there a more elegant way?

try {
            $branches = User::findOrFail($user->id)->branches()->get();
            return view('profile.show', compact('user', 'branches'));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return view('profile.show', compact('user'));
        }
0 likes
2 replies
Snapey's avatar

return view('profile.show', compact('user'));is it likely that your user does not exist? The code you show will only error if the user does not exist... not if there are no branches

also, I thought is was companies with branches?

Better solution, forget try catch, and you already have $user

$user->load('branches');

return view('profile.show', compact('user'));
mcbates's avatar
mcbates
OP
Best Answer
Level 4

Actually, turns out I don't need to manually pass it. User (= Company) already has the related data, so I can loop over it (and return empty) like this:

@forelse ($user->branches as $branch)
// Loop over branches
@empty
// No related branches found
@endforelse

Please or to participate in this conversation.