Jenski
Jenski

Reputation: 1468

firstOrFail() function behaviour in Laravel

I have a factory with this line in it:

$channel = \App\Model\Channel::firstOrFail();

How is the id set? I know there is a function like

$channel = \App\Model\Channel::firstOrFail($id);

But what's the difference to the one above and how do you set it?

Upvotes: 1

Views: 1990

Answers (2)

lufc
lufc

Reputation: 2040

$channel = \App\Model\Channel::firstOrFail();

Will just return the first Channel in the model, usually the one with the lowest ID number. This could be used to check that there are any Channels in the database, e.g. you want to know that there's a possible Channel for users to select.

$id = ['id'];
$channel = \App\Model\Channel::firstOrFail($id);

Is the same but will only return the id of the first model in the database.

If you want to return an element with a specific ID you should use

$channel = \App\Model\Channel::find($id)->firstOrFail();

or

$channel = \App\Model\Channel::findOrFail($id);

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50787

firstOrFail just calls ->take(1)->get()->first()

If that returns null, then it throws a ModelNotFoundException and sets the model to the current query builder instance.

Channel, in your case, extends Model, which uses the Query Builder under the hood, which has the firstOrFail function.

If you want to set the id then it's:

$channel = \App\Model\Channel::findOrFail($id);

Furthermore, it's unnecessary to fully qualify your namespace, so you're free to just do:

$channel = App\Model\Channel::findOrFail($id);

Upvotes: 3

Related Questions