Ad

Checking If Empty Or Using A Try/catch?

- 1 answer

I am spinning up a application in Laravel 5 and I am relatively new to the framework. I am checking if a user's unique key is in the request and the question I'm asking could be across the framework. I am querying the database and using a firstOrFail. I was wondering if there are any advantages to using a try/catch and catching the error or checking if empty?

try {
    User::where('identifier', $request->key)->firstOrFail();        
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    // Display error
}

versus

$user = User::where('identifier', $request->key)->first();
if (empty($user)) {
    // Display error
}
Ad

Answer

As far as the try/catch part of your question, I'd avoid the try/catch for a couple reasons. The small reason is that try/catch is fairly slow in PHP. The big reason is that the operation can fail for reasons other than a ModelNotFoundException, and your code will miss that.

Ad
source: stackoverflow.com
Ad