Laravel - find by custom column or fail

2019-03-14 05:59发布

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');

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-14 06:21

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)
查看更多
Animai°情兽
3楼-- · 2019-03-14 06:33

Try it like this:

Page::where('slug', '=', 'about')->firstOrFail();
查看更多
登录 后发表回答