1

In my package, before I perform a query on my database I check if some of the params provided are valid:

//check
if(!$this->checkId($id)) //error

//do the query
$user = User::find($id);

What's the best way to handle this in a laravel package?

Throw an error? If so, which kind? Do an app abort?

2 Answers 2

1

Using findOrFail()

There is a pretty good method that Laravel provides just for this case called findOrFail().

What you can do is use that and then catch the exception.

try {
    $user = User::findOrFail($queryParam);
} catch(ModelNotFoundException $e) {
    // Do things that should happen here if your query parameter does not exist.
}

If you do not wish to catch it here, you can setup a listener for this exception. You can place it anywhere you wish as long as it's being autoloaded.

use Illuminate\Database\Eloquent\ModelNotFoundException;

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

Throwing an exception

If all you want to do is throw an error if a query param isn't available, you can throw any of the exceptions found here... https://github.com/symfony/symfony/tree/master/src/Symfony/Component/HttpKernel/Exception

If none suit you, you can create your own and just extend Symfony\Component\HttpKernel\Exception\HttpException and throw new YourCustomException($statusCode, $message);. Just follow what they've done in the other exception classes and it should be fairly easy.

Then you can modify the the "exception listener" to catch YourCustomException.

Here is a tutorial I found... http://fideloper.com/laravel4-error-handling

Sign up to request clarification or add additional context in comments.

3 Comments

It might also be worth looking into Model::findOrNew().
Thanks but this does not answer the question, I need to know how to throw an error, if you re-read the question you'll see that I do not need to use find or fail or throw an error on a query, but just on a standard method.
You may want to clarify your question because you are asking "What's the best way to handle this in a laravel package?" and I gave you what I thought was the best way.
0

I would use Event Listeners for the most control.

Create an events.php in your app directory and include it in app/start/global.php Or, you can register anywhere in your package.

Create a listener:

Event::listen('paramCheck.noId', function($id)
{

    // do some logic, log something, return something, throw an error...

});

Then fire the event from whenever you need to:

if(!$this->checkId($id))
    $returnFromEvent = Event::fire('paramCheck.noId', array($id));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.