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.
Example 1
find single Id
public function index()
{
$blogs = Blog::find(1); // find single value
dd($blogs);
}
Example 2
find multiple ids in array
public function index()
{
$blogs = Blog::find([1, 2, 3]);
dd($blogs);
}
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",
}
Example 4
find multiple ids with title and image
Blog::find([1, 2, 3], ['title', 'image']);
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",
},
],
}
>>>
Example 5
find first id between primary keys
Blog::find([1, 2, 3])->first();
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",
}
>>>
find last id between primary keys
Blog::find([1, 2, 3])->last();
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",
}
>>>
Read also
3 way to install bootstrap 5 in laravel 8
Laravel php artisan inspire command
Laravel clear cache without using artisan command