I am following this tutorial for creating user roles, views, etc. And I've created all the views, the controller and all that jazz.
In my controller I've added a 'guard' clause for the show() method - if somebody were to try to access the ID of the user that doesn't exist, I'd redirect them to the users screen with a dismissable warning.
public function show($id)
{
$user = User::find($id);
$view = redirect()->route('users.index')
->with('userNotFound', "User with the ID {$id} doesn't exist.");
if ($user) {
$view = view('users.show', compact('user'));
}
return $view;
}
In my users/show.blade.php I have a 'back' button <a class="btn btn-primary" href="{{ route('users.index') }}">Back</a>, and when I'd click it, I'd be sent back to the users/index.blade.php screen with the notice that the ID of the user (on whose screen I was just a second ago) doesn't exist.
Which was odd. So I've placed the $view variable in the else part of the conditional and all is well
public function show($id)
{
$user = User::find($id);
if ($user) {
$view = view('users.show', compact('user'));
} else {
$view = redirect()->route('users.index')
->with('userNotFound', "User with the ID {$id} doesn't exist.");
}
return $view;
}
Notice won't be shown when I click the back button.
The notice was outputted like this:
@if ($message = session('success'))
<div class="alert alert-success">
{{ $message }}
</div>
@elseif($message = session('userNotFound'))
<div class="alert alert-warning alert-dismissible fade show">
{{ $message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
in my users/index.blade.php
I've stored the redirect and the view in a variable to avoid using multiple returns.
But what bothers me is: why was this happening in the first place?
The back button will make a request towards the users.index route which is governed by the index() method in my UserController, the redirect part which is in the show() method should never been invoked.
Why did this happen and what am I missing?