Laravel - find by custom column or fail

2019-03-14 06:06发布

问题:

There's findOrFail() method which throws 404 if nothing was found, e.g.:

User::findOrFail(1);

How can I find an entity by custom column or fail, something like this:

Page::findBySlugOrFail('about');

回答1:

Try it like this:

Page::where('slug', '=', 'about')->firstOrFail();


回答2:

It took at least two hours to realize that if you chain firstOrFail() method after where() in Laravel 5.6, it basically tries to retrieve the first record of the table and removes where clauses. So call firstOrFail before where.

Model::firstOrFail()->where('something', $value)