Using ModelNotFoundException

Try this

  try {

      $user = User::findOrFail($request->input('user_id'));

    } catch (ModelNotFoundException $exception) {

       return back()->withError($exception->getMessage())->withInput();
    }

And to show error, use this code in your blade file.

 @if (session('error'))
   <div class="alert alert-danger">{{ session('error') }}</div>
 @endif

And of course use this top of your controller

use Illuminate\Database\Eloquent\ModelNotFoundException;  

In Laravel by default there is an error handler declared in app/start/global.php which looks something like this:

App::error(function(Exception $exception, $code) {
    Log::error($exception);
});

This handler basically catches every error if there are no other specific handler were declared. To declare a specific (only for one type of error) you may use something like following in your global.php file:

App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception) {

    // Log the error
    Log::error($exception);

    // Redirect to error route with any message
    return Redirect::to('error')->with('message', $exception->getMessage());
});

it's better to declare an error handler globally so you don't have to deal with it in every model/controller. To declare any specific error handler, remember to declare it after (bottom of it) the default error handler because error handlers propagates from most to specific to generic.

Read more about Errors & Logging.


Just use namespace

try {
    $menus = Menu::where('parent_id', '>', 100)->firstOrFail();
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    $message = 'Invalid parent_id.';
    return Redirect::to('error')->with('message', $message);
}

Or refer it to an external name with an alias

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;

When you use the render() function in Laravel 8.x and higher versions, you will encounter 500 Internal Server Error. This is because with Laravel 8.x errors are checked within the register() function (Please check this link)

I'm leaving a working example here:

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    public function register()
    {

        $this->renderable(function (ModelNotFoundException $e, $request) {
            return response()->json(['status' => 'failed', 'message' => 'Model not found'], 404);
        });
        $this->renderable(function (NotFoundHttpException $e, $request) {
            return response()->json(['status' => 'failed', 'message' => 'Data not found'], 404);
        });
    }
}

Tags:

Laravel