Victor Leal
Victor Leal

Reputation: 1065

Autoload Laravel Exceptions

I'm working with Eloquent Models, which throw the ModelNotFound exception when we use the findOrFail() method.

I have a global handler to this exception, set in the file global.php.

But I would like to show to the user appropriate messages, so I have to handle these exceptions locally, using try/catch.

The "problem" is that I wouldn't like to import the file all the time, or use the complete namespace like this:

try {
    Model::findOrFail();
} catch(Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    //do something here
}

Isn't there a way to autoload this file?

Upvotes: 0

Views: 234

Answers (2)

user1669496
user1669496

Reputation: 33058

I just tested this and it seems to work fine. What I did was added the following to the aliases array in config/app.php.

'ModelNotFoundException' => Illuminate\Database\Eloquent\ModelNotFoundException::class,

And now you should be able to catch that exception by doing the following...

try {
    throw new \ModelNotFoundException('Some Message');
} catch (\ModelNotFoundException $e) {
    echo $e->getMessage();  // Should echo "Some Message"
}

Upvotes: 2

camelCase
camelCase

Reputation: 5598

I think I understand the question; if all you what you want to do is autoload that global.php file, you can simply add it to your composer.json file like:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/global.php" // <-- Or wherever your file lives
    ]

Then just execute a composer dump auto-load -o or the like, and now you'll have access to this file/all functions within the file, anywhere in your application.

Upvotes: 0

Related Questions