简体   繁体   中英

Laravel Eloquent firstOrFail returns all records in table

I'm trying to retrieve a row in my eloquent model. What I want to do is first search to see if it exists or throw an exception. In the Laravel docs, it says I can use firstOrFail or findOrFail . The eloquent query is as follows:

Game::where('game', 'game-name')->firstOrFail()->remember(60)->get()

This works for finding the record and throwing an exception if not found however it returns all rows as a result. What I would like to do is just return the row that I've searched for. I am not indexing by primary key in this example so findOrFail doesn't work.

If I replace ->get() with ->first() all it does is return the first row in the table. It ignores the ::where() .

EDIT: When I removed ->get() and ->remember() it returned the desired row however I still would like to cache the query but when I use ->remember() and print_r on the result, the entire eloquent model is dumped.

EDIT2: All is resolved. I always confuse the place of ->remember() . The correct way to do this is:

Game::where('game', 'game-name')->remember(60)->firstOrFail()

All is resolved.
I always confuse the place of ->remember() .
The correct way to do this is:

Game::where('game', 'game-name')->remember(60)->firstOrFail()

Wrong result seems to be cached, avoid using remember until you have the right query. If you use get it will return a Collection instance. findOrFail expect an id as the first parameter. Get the first result from your query with first and then check if it is empty to throw an Exception

Game::where('game', 'game-name')->first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM