What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()
find($id)
takes an id and returns a single model. If no matching model exist, it returnsnull
.findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.first()
returns the first record found in the database. If no matching model exist, it returnsnull
.firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.get()
returns a collection of models matching the query.pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was calledlists
.toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
findOrFail returning the correct and also a wrong record
You're passing the whole Location
model to findOrFail
.
When you type hint the id, it does the query to find the Location
model for you, and saves it to the variable. This is causing the findOrFail
to look for every key in the collection you passed it. The second row its finding is due to the id
existing in the phone number of location 2 probably truncated by the -
after.
Instead of type hinting $location
in the method, just do
public function show(ShowLocationRequest $request, $Location)
This will cause your query to only search for the id in your route, instead of every key in the location model.
Option two is to leave the type hinting and load the relationships afterwards
public function show(ShowLocationRequest $request, Location $location)
{
$location->load('company,name');
}
Laravel Find and first not working together properly
You can use with()
static method, please refer to doc
For example:
$employee = Employee::with('company')->find($id);
Or you can find the record and load the relations
$employee = Employee::findOrFail($id)->load('company');
Laravel retreive data from database order by creation date
You must have got error when using order_by
as its not the syntax in Laravel.
$localnews = Articles::whereHas('sous_categories',
function ($query) {
$query->where('id', '15')->orderBy('created_at', 'desc');
})->first();
Please have a look at official documentation to help you with.
And when using first()
you don't need to use get()
.
get()
we use to fetch multidimensional associative array.first()
we use to fetch one record which matches first.
Here is concise difference between all functions you will use then after. link.
join, trying to get property of non-object, - first, - firstorfail, - get()
first()
and firstOrFail()
will retrieve one record - the first record it finds if it exists.
firstOrFail()
is also only available for Eloquent. You are using the query builder so that method does not exist.
Finally, get()
is what you are looking for. It "gets" all matching records, but the query builder's get()
method returns an array of records.
Your view is not reflecting that. Your view assumes that there is only one record so you are getting the Trying to get property of non-object
error message. If you get multiple records but you try to do this: $panitia->id_panitia
, how is the code supposed to know which record's id it's supposed to get? It can't because it's trying to access the id of the array, which doesn't make sense. You need to loop through and change your lihat
view to something like this:
Note the foreach:
@foreach ($panitia as $pan)
<div class="form-group">
<label for="isbn" class="col-sm-2 control-label">Id Panitia</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="id_panitia" placeholder="{{ $pan->id_panitia}}" readonly>
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" placeholder="{{$pan->username}}" readonly>
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="nama" placeholder="{{$pan->nama}}" readonly>
</div>
</div>
@endforeach
Also, I added quotation marks around the double curly braces.
Combine categories tree
collect($arr)
->groupBy(function ($item) {
return $item['id'] . $item['child']['id'];
})
->map(function ($group) {
$first = $group->first();
$first['child']['child'] = $group->pluck('child.child')->toArray();
return $first;
})
->values()
->toArray()
Trying to get property of non-object when iterating results
From the docs:
The findOrFail .. methods will retrieve the first result of the query;
Note "first result" - not a Collection of results, but one result. So $details
here is a single model instance (if one is found):
$details = Offer::findOrFail($id);
You've verified this yourself by checking $details
, you can see it is a single model, not a Collection:
{
"id": 1,
...
}
A Collection of one model would look something like this:
[{
"id": 1,
...
}]
But the view attempts to iterate over that single model:
@foreach($details as $detail)
Since $details
is a single model instance, this will attempt to iterate over its properties, which will fail.
If you're only passing a single model to your view, just remove the @foreach
iteration to display it. It would also make sense to change your variable name in the controller to $detail
since it is singular.
<div class="container row d-flex justify-content-center">
<div class="col-md-4 mb-4 float-left">
<div class="card">
<div class="card-body text-center">
<h5 class="mt-0 mb-1 mb-2">{{ $detail->title }}</h5>
Side-note: There are many comments and answers here saying the spaces between your variable names and the object operator ->
are wrong and causing the error. In fact spaces work fine (amazingly, at least to me), though as you can tell from the number of comments it is very unusual, and I expect considered poor coding style.
Property [role] does not exist on this collection instance.
As the error message is shown
"Property [role] does not exist on this collection instance."
It indicates that $user
is an instance of Collection
You have to change
$user = User::where('id', $request->user_id)->get();
To this
$user = User::where('id', $request->user_id)->first();
get()
: returns a collection of models matching the query.first()
: returns the first record found in the database. If no matching model exist, it returns null.
more info
Related Topics
Two Simultaneous Ajax Requests Won't Run in Parallel
Get the Sum of All Digits in a Numeric String
Codeigniter - How to Catch Db Errors
Cakephp 2.0 - How to Make Custom Error Pages
Getting Http Code in PHP Using Curl
Laravel Stylesheets and JavaScript Don't Load for Non-Base Routes
Generate Random 5 Characters String
Using MySQLi from Another Class in PHP
Beautiful Way to Remove Get-Variables with PHP
Fatal Error: Maximum Execution Time of 300 Seconds Exceeded