Skip to content
Advertisement

Laravel 5 : How to use findOrFail() method?

I just follow some tutorial and so far what I do is :

my App/Exceptions/Handler.php

<?php
...
use IlluminateDatabaseEloquentModelNotFoundException;
...
public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException){
        abort(404);
    }
        return parent::render($request, $e);
}

and my UsersController looks like this :

...
public function edit($id)
{
    $data = User::findOrFail($id);
    $roles = Role::where('title', '!=', 'Super Admin')->get();
    return View('admin.user.edit', compact(['data', 'roles']));
}
...

with the above code if I visit http://my.url/users/10/edit I get NotFoundHttpException in Application.php line 901:, yes because there is no id 10 in my record, but with User::find($id); I get normal view without data, since no id 10 in my record.

What I want is show default 404 then redirect to somewhere or return something if record not found with User::findOrFail($id); ? How I can do that ?

Thanks, any help appreciated.

ps: .env APP_DEBUG = true

Advertisement

Answer

This does what you asked. No need for exceptions.

public function edit($id)
{
    $data = User::find($id);
    if ($data == null) {
        // User not found, show 404 or whatever you want to do
        // example:
        return View('admin.user.notFound', [], 404);
    } else {
        $roles = Role::where('title', '!=', 'Super Admin')->get();
        return View('admin.user.edit', compact(['data', 'roles']));
    }
}

Your exception handler is not necessary as it is. Regarding IlluminateDatabaseEloquentModelNotFoundException:

If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is not necessary to write explicit checks to return 404 responses when using [findOrFail()].

Also, I’m pretty sure you get the exception page instead of 404 now because you’re in debug mode.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement