Home > Enterprise >  Laravel: How do I raise a 404 error instead of a 50X error when ID for resource is non-integer
Laravel: How do I raise a 404 error instead of a 50X error when ID for resource is non-integer

Time:07-09

I created a simple crud in Laravel, but I'm having a problem:

I am using Illuminate\Support\Facades\Route::resource method, this is my routes/web.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});

Route::get('dashboard', [App\Http\Controllers\PageController::class, 'dashboard'])
    ->middleware('auth:sanctum')
    ->name('dashboard');

Route::resource('notes', App\Http\Controllers\NoteController::class)
    ->middleware('auth:sanctum');

When I go to /notes/a where 'a' is supposed to be the index of the note I want to see, I get a 500 error:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "a"

select * from "notes" where "id" = a limit 1

At this point, none of my code has yet run. How can I catch this error to raise a 404 error instead?

CodePudding user response:

you can use firstOrFail() or findOrFail example code below

public function find(Request $request){
    return Note::findOrFail($request->id);
}

CodePudding user response:

You can use abort(404) which abort your code if no data found.

public function findNote($id)
{
    $note = Note::find($id)
    
    if($note == null)
    {
    abort(404);
    }
}

CodePudding user response:

you can use try catch block to modify the response

public function whatEverMyMethodIs( Request $request ) {

    try {
        return ModeL::find( $request->input('id') );
    } catch (\Throwable $th) {
        return response()->json(['message' => $th->getMessage()], 404 );
    }
    
}
  • Related