-2

I am using try in Laravel 5.5 like this...

try {
        $fruit = Fruit::findOrFail($id);
    }

But I would like to check that not only that it finds the Fruit with the supplied ID but that it also has a fruit_color of 'red'

Do I need to do this with a 'with' statement?

I know I can run another check afterwards but wondered if I could do this all in one statement?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 2
    Possible duplicate of [Laravel - find by custom column or fail](https://stackoverflow.com/questions/29212982/laravel-find-by-custom-column-or-fail) – Camilo Feb 16 '18 at 00:06

3 Answers3

2

A few things. First, throwing an exception here is the wrong way to handle the ‘if’ situation. If you plan on a situation where a value isn’t return, then this isn’t the proper use of an exception. To answer your question:

$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->get();

This returns a collection of items meeting your criteria. Next to test if the collection is empty (no fruit) you can do the following:

if($fruit->isEmpty()) {
    //handle empty collection
}

Hope this helps! The Laravel documents for collections kicks a**. I’d recommend reading further there.

Luke
  • 943
  • 6
  • 12
1

You just need to add your extra conditions in before you call the find:

try {
    $fruit = Fruit::where('fruit_color', 'red')->findOrFail($id);
}
patricus
  • 59,488
  • 15
  • 143
  • 145
  • A try statement should catch.. However, excluding the try, using `findOrFail()` at the end after the `where` methods seems to work when you need to filter the db results by particular where conditions and throw a 404 if there are no matches, all in one go. – Wade Apr 02 '21 at 18:09
0

Try this code

$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->first();
Boghani Chirag
  • 217
  • 1
  • 8