Ad

Laravel: Route Model Binding Exception Handling In Ajax Request

- 1 answer

Laravel version 7.x

I am submitting the create and edit methods via ajax request and its working fine. But, in my application there is a module which is dependent on a parent module, such as: Employee and EmployeeEmergency. So I added the Employee $Employee parameter in the create method and the route to handle this request.

However, If the Employee identifier is correct, it works fine. But, if the identifier is invalid then it throws an exception.

{
    "message": "No query results for model [App\\Employee] $arrayModel->token",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
    ...
}

I can handle this exception by removing the route model binding and the authenticate the Employee manually. But, that will just increase the code unnecessarily.

I want to handle this exception with a proper response, something like Employee identifier is invalid or something like that to notify the user and prevent error.

Employee.php

class Employee extends Model
{
    ...

    public function getRouteKeyName()
    {
        return 'token';
    }

    ...
}

EmployeeEmergencyController.php

use App\Employee;
use App\EmployeeEmergency;

class EmployeeEmergencyController extends Controller
{
    public function create(Employee $employee)
    {
        ...
    }
}

Web.php

Route::get('employee-emergency/create/{employee}', '[email protected]')
    ->name('admin.employee-emergency.create');

Is there any solution for this out of the box..?

Ad

Answer

First, let me note that the error you receive, is way bigger than usual, because you have APP_DEBUG set to true and APP_ENV set to local in your .env, if APP_DEBUG is false and APP_ENV= production, the error should be reduced to a plain 404.

Second, if you look in the docs: https://laravel.com/docs/6.x/routing#explicit-binding

You can see that you can customize the behaviour like so:

//App\Providers\RouteServiceProvider.php
public function boot()
{
    parent::boot();

    Route::bind('employee', function ($id) {
        $employee = App\Employee::where('id', $id)->first();
        if (empty($employee)) {
            throw new \Exception('Employee not found');
        }
        return $employee
    });
}

EDIT:

  • Updated laravel link
  • Updated answer itself
Ad
source: stackoverflow.com
Ad