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?
So, for performance and memory consumption, SB query is definitely better than Eloquent Query Builder.
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.
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.
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.
Maybe you can use the firstOrFail() function of Laravel.
Task::where('column_name', '=' ,'column_data')->firstOrFail();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With