Why not do it from the controller? Why exactly would you do it from the view?
Redirect to 404 from a blade view template
Hey guys,
I have a member profile system set up which uses the username as part of their profile page url.
Right now if any non-existing profile is called it throws non-object errors (as there is no user object being found to populate the data on the page).
To get around this I've tried using the following at the top of the profile template but it's not doing what I expected.
@php
if (!$user) {
return abort(404);
}
@endphp
I was hoping that when an empty user object is found it would redirect to a 404 page, but this isn't working. Instead I'm getting error exception errors. Am I going about this the wrong way?
Would it be better to check the user object exists in the route instead, before serving the template?
You can also use route model binding, which does this automatically (issues a 404) if the model isn't found. https://laravel.com/docs/5.5/routing#route-model-binding
You can also use findOrFail(), firstOrFail(), etc. https://laravel.com/docs/5.5/eloquent#retrieving-single-models
Please or to participate in this conversation.