DEV Community

loading...
Cover image for Laravel find() method Tips

Laravel find() method Tips

larainfo
Full Stack Developer | Laravel | Livewire | Vue Js Nodejs, tailwind css
Originally published at larainfo.com ・2 min read

In this short tutorial we will see some example of laravel find methods . find method returns the model that has a primary key matching the given key . it will return also all models which have a primary key in given array.

visit my website

Example 1

find single Id

public function index()
    {
        $blogs = Blog::find(1); // find single value
        dd($blogs);
} 
Enter fullscreen mode Exit fullscreen mode

Example 2

find multiple ids in array

public function index()
    {
        $blogs = Blog::find([1, 2, 3]);
        dd($blogs);
    }
Enter fullscreen mode Exit fullscreen mode

Example 3

find single id with only title

php artisan ti

>>> Blog::find(1,['title']);
[!] Aliasing 'Blog' to 'App\Models\Blog' for this Tinker session.
=> App\Models\Blog {#4206
   title: "second blogs",
  }

Enter fullscreen mode Exit fullscreen mode

Example 4

find multiple ids with title and image

Blog::find([1, 2, 3], ['title', 'image']);
Enter fullscreen mode Exit fullscreen mode

output:

=> Illuminate\Database\Eloquent\Collection {#4102
   all: [
    App\Models\Blog {#4349
     title: "second blogs",
     image: "blogs/HFvoGKizxpZfsBYlXAb43jlbEzr5CvIuJoEnQCrJ.png",
    },
    App\Models\Blog {#4141
     title: "First Blogs",
     image: "blogs/l0f4fPNcocy8UVHB1RsWvM8M979VjULzhB2dHiW7.png",
    },
    App\Models\Blog {#3413
     title: "thirds blog",
     image: "blogs/pObdTv4aoUUci1OyUxmj4MQNvS7ega7SZtf3mBEQ.png",
    },
   ],
  }
>>> 
Enter fullscreen mode Exit fullscreen mode

Example 5
find first id between primary keys

Blog::find([1, 2, 3])->first();
Enter fullscreen mode Exit fullscreen mode

output:

=> App\Models\Blog {#4350
   id: 1,
   title: "second blogs",
   description: "second blogs descrition",
   image: "blogs/HFvoGKizxpZfsBYlXAb43jlbEzr5CvIuJoEnQCrJ.png",
   created_at: "2021-05-27 16:58:37",
   updated_at: "2021-06-12 06:46:33",
  }
>>> 

Enter fullscreen mode Exit fullscreen mode

find last id between primary keys

Blog::find([1, 2, 3])->last();
Enter fullscreen mode Exit fullscreen mode

output

=> App\Models\Blog {#4355
   id: 3,
   title: "thirds blog",
   description: "third blogs descritions",
   image: "blogs/pObdTv4aoUUci1OyUxmj4MQNvS7ega7SZtf3mBEQ.png",
   created_at: "2021-06-12 07:01:13",
   updated_at: "2021-06-12 07:01:13",
  }
>>> 

Enter fullscreen mode Exit fullscreen mode

visit my website

Read also

3 way to install bootstrap 5 in laravel 8
Laravel php artisan inspire command
Laravel clear cache without using artisan command

Discussion (0)