Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Throw error from controller

Tags:

php

laravel

I have a project and if I want to access partner/X I got get property of non object error, becouse I have less partners than X.

My question. How to tell the controller, that if the result of the modelquery is empty, than throw a 404 error?

My code is so far:

public function showPartner($id = 0){

   //Only allow numerical values    
  if ($id > 0){

    $partner = Partner::find($id);

    if (empty($partner)){
        return ???
    }
  }
}
like image 400
Feralheart Avatar asked Sep 09 '17 14:09

Feralheart


People also ask

How do you do error reporting in laravel?

Through your config/app. php , set 'debug' => env('APP_DEBUG', false), to true . Or in a better way, check out your . env file and make sure to set the debug element to true.

What is exception handler in laravel?

By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler.


2 Answers

Laravel has a specific method for that. If you use findOrFail($id), it will throw an Illuminate\Database\Eloquent\ModelNotFoundException, so there's no need to throw an Exception by yourself.

If you mean "show the user an 404 error" instead of literally throwing an Exception, then catch it and abort():

public function showPartner($id = 0){

//Only allow numerical values    
    if ($id > 0){
        try {
            $partner = Partner::find($id);
            // do your work
        }
        catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            abort(404, "The Partner was not found");
        }
    }
}

Read more about this here.

like image 178
ishegg Avatar answered Oct 03 '22 22:10

ishegg


Use the abort() helper:

abort(404);

There's also abort_if() and abort_unless() if you prefer. Whichever one you choose, you can pass it the required status code.

like image 21
Matthew Daly Avatar answered Oct 03 '22 20:10

Matthew Daly