In this short tutorial, we will see some examples of Laravel’s find
method. The find
method returns the model that has a primary key matching the given key. It can also return all models which have a primary key in the 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);
}
Output :
Illuminate\Database\Eloquent\Collection {#1002 ▼
#items: array:3 [▼
0 => App\Models\Blog {#1003 ▶}
1 => App\Models\Blog {#597 ▶}
2 => App\Models\Blog {#965 ▶}
]
}
Example 3
find single id with only title.
public function index()
{
$blogs = Blog::find(1, ['title']);
dd($blogs);
}
Output:
>>> Blog::find(1,['title']);
[!] Aliasing 'Blog' to 'App\Models\Blog' for this Tinker session.
=> App\Models\Blog {#4206
title: "second blogs",
}
Note: In the following examples, we will use Laravel Tinker.
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",
}
>>>