Reputation: 197
I have a method that checks if a role is equal to 1 and then sends back some data. The method looks like so:
if($user->role == 1) {
$dmca = Dmca::get()->take(5);
$data = [
'status' => 200,
'data' => $dmca
];
return response($data);
} else {
$dmca = Dmca::where('client', $request->user_id)->get()->take(5);
$data = [
'status' => 200,
'data' => $dmca
];
return response($data);
}
}
On the dump and die of the $user instance, you can see the role is there and is set. But on return, I get the error
#attributes: array:11 [
"id" => 1
"name" => null
"email" => "[email protected]"
"model_name" => "man"
"subscribed" => 0
"email_verified_at" => null
"password" => "$2y$10$yy1Yj.GGez7efEdFdkjaf.RlQS17Zc7QYUANz3RvdE00fVm0f9AYq"
"role" => 1
"remember_token" => null
"created_at" => "2020-07-05 17:54:38"
"updated_at" => "2020-07-05 17:54:38"
]
Getting the following error when the axios returns
"Property [role] does not exist on this collection instance."
Upvotes: 0
Views: 1330
Reputation: 6088
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.Upvotes: 2