Feralheart
Feralheart

Reputation: 1920

Laravel: Throw error from controller

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 ???
    }
  }
}

Upvotes: 12

Views: 28677

Answers (2)

ishegg
ishegg

Reputation: 9927

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.

Upvotes: 10

Matthew Daly
Matthew Daly

Reputation: 9476

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.

Upvotes: 7

Related Questions