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?
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
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