Home » Php » php – laravel: protecting against query that comes back null

php – laravel: protecting against query that comes back null

Posted by: admin February 25, 2020 Leave a comment

Questions:

I had a query that checks the User table for a user who has a specific code and grabs that user , and sets it to $mainCustomer. I just realized there are situations where there might not be a User with that code. I thought my check underneath that for ! $mainCustomer would cover me but I believe I might get an error with the query itself if it’s null. How can I protect against an error with the query?

        $mainCustomer = User::where('code', '=', $value_code)->first();

        if (! $mainCustomer) {
            log_info("doesn't exist");

            return;
        }
How to&Answers:

return User::where('code', '=', $value_code)->firstOrFail();

The method will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods.

Is this what you are after?