In my application, I have the concept of a user profile. The information that gets displayed differs depending on whether the user is viewing their own profile or another user's profile. Here's a simplified view of UsersController@show
:
public function show($id)
{
$user = User::findOrFail($id);
$currentUser = Auth::user();
return view ('users.show', compact('user', 'currentUser'));
}
In my view, I end up having to write code that looks like:
@if ($currentUser === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
@include ('partials._search')
</div>
</div>
</section>
@endif
This seems like a clumsy implementation, especially for a language like Laravel. Is there a more concise way to achieve the same result in my views?
Not really. You need to check if current user is the viewed user somewhere - either in the controller or in the view.
You could simplify your code a bit though:
public function show($id)
{
$user = User::findOrFail($id);
return view ('users.show', compact('user'));
}
@if (Auth::id() === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
@include ('partials._search')
</div>
</div>
</section>
@endif
There are some other options like returning different blade templates depending on whether the current user is the same as the viewed user, but if the only difference would be a few @ifs I would keep it in one template.