Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent query similar to findorfail

I would like to look up and return an object referenced by a different column to that of id.

As far as I know there isn't another method similar to Task::findOrFail($id) but that can reference another field. For example:

Task::findOrFail('column_name' = 'column_data');

I'm currently using

Task::where('tid' , '=', $tid)->first();

Is this possible?

like image 592
Michael Avatar asked Apr 09 '14 15:04

Michael


People also ask

Which is better eloquent or query builder in Laravel?

So, for performance and memory consumption, SB query is definitely better than Eloquent Query Builder.

What is the difference between find and findOrFail in Laravel?

find($id) takes an id and returns a single model. If no matching model exist, it returns null . findOrFail($id) takes an id and returns a single model.

What is the use of findOrFail in Laravel?

findOrFail is great because it ensures you'll end up with a model instance. No more “Attempt to read property on null” exceptions. $title = Post::findOrFail($id)->title; Another benefit is that Laravel returns a 404 response for you when the model doesn't exist.

What is the difference between Get () and first () in Laravel?

The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.


1 Answers

Maybe you can use the firstOrFail() function of Laravel.

Task::where('column_name', '=' ,'column_data')->firstOrFail();
like image 151
Needpoule Avatar answered Oct 11 '22 10:10

Needpoule