What is The Difference Between find(), findOrFail(), firstOrFail()
find($id) Take single argument and returns a single model. If no matching model exists, it will return null.
#find()
DB::table('packages')->find(16)
== OR ==
Packages::find(16)
#Output:
{
"id": 16,
"package_name": "test16",
"package_amount": "5000",
"package_status": 0,
"created_at": "2020-03-05 23:09:12",
"updated_at": "2020-03-05 23:09:12",
}
findOrFail($id) takes a single argument and returns it will return the first record from the top otherwise it will return an error.
#findOrFail()
DB::table('packages')->findOrFail(18)
== OR ==
Packages::findOrFail(18)
#Output:
{
"id": 18,
"package_name": "test18",
"package_amount": "6000",
"package_status": 1,
"created_at": "2020-03-05 22:00:00",
"updated_at": "2020-03-05 22:02:12",
}
first() returns the first record found in the database. if no match model exist then it will returns null.
#first()
DB::table('packages')->first()
== OR ==
Packages::first()
#Output:
{
"id": 2,
"package_name": "test2",
"package_amount": "10000",
"package_status": 1,
"created_at": "2020-02-04 22:57:30",
"updated_at": "2020-02-15 02:49:50",
}
firstOrFail() returns the first record found in the database. if no matching model exists it will return an error.
#firstOrFail()
Packages::findOrFail(3)
#Output:
{
"id": 3,
"package_name": "test3",
"package_amount": "7000",
"package_status": 0,
"created_at": "2020-02-05 14:25:40",
"updated_at": "2020-02-08 10:00:45",
}
get() returns a collection of models matching the query.
#get()
DB::table('packages')->get()
== OR ==
Packages::get()
#Output:
data:[
{
"id": 2,
"package_name": "test2",
"package_amount": "10000",
"package_status": 1,
"created_at": "2020-02-04 22:57:30",
"updated_at": "2020-02-15 02:49:50",
}
{
"id": 3,
"package_name": "test3",
"package_amount": "7000",
"package_status": 0,
"created_at": "2020-02-05 14:25:40",
"updated_at": "2020-02-08 10:00:45",
}
...
]
pluck($column) take single argument and returns a collection of just the values in the given column.
#pluck()
DB::table('packages')->pluck('package_name')
== OR ==
Packages::pluck('package_name')
#Output:
data:[
"test2",
"test3",
...
]
toArray() converts the model/collection into a simple php array.
#toArray()
DB::table('packages')->first()->toArray()
== OR ==
Packages::first()->toArray()
#Output:
[
"id": 2,
"package_name": "test2",
"package_amount": "10000",
"package_status": 1,
"created_at": "2020-02-04 22:57:30",
"updated_at": "2020-02-15 02:49:50",
]