Reputation: 4340
I was in the process of building a small API system using laravel. This is a small piece of code from it which searches for user, and if it exists, sends a json response back. When I ran this code such that it should return no user(usercontent is {}), the is_null still returns false. I thought it should return true in this case. I had planned to use it in my code to check if certain users exist, but now it seems to be failing everytime.
have i misunderstood something? Can someone explain what I missed? Thanks.
Response code:
if($user)
{
return Response::json(array(
'error' => 'true',
'message' => 'User exists.',
'user' => is_null($user),
'usertype' => gettype($user),
'usercontent' => $user
), 400);
}
Response json:
{
"error":"true",
"message":"User exists.",
"user":false,
"usertype":"object",
"usercontent":{}
}
EDIT:
i did a
var_dump($user);
var_dump(empty($user));
which seem to return
object(Illuminate\Database\Eloquent\Collection)#201 (1) { ["items":protected]=> array(0) { } }
bool(false)
EDIT 2:
$user = User::where('mobile_number', '=', Request::get('mobile_number'))
->orwhere('email_id', '=', Request::get('email_id'))
->take(1)
->get();
Upvotes: 1
Views: 1870
Reputation: 809
Based on your edited question, if you use take()
the returned object would be a Illuminate\Database\Eloquent\Collection
, instead of Illuminate\Database\Eloquent\Model
, even if the returned collection has one model object, or none (in that case, an empty collection will be returned).
Instead, you can use find()
and get a model object using the primary key, or add first()
to your query to get the first result from the query as a model object. These two methods will return null
if the query does not match an entry.
For example:
$user = User::find(1);
Output:
{
"error":"true",
"message":"User exists.",
"user":false,
"usertype":"object",
"usercontent":{
"timestamps":true,
"autoHashPasswordAttributes":true,
"validationErrors":{},
"throwOnValidation":false,
"autoHydrateEntityFromInput":false,
"forceEntityHydrationFromInput":false,
"autoPurgeRedundantAttributes":false,
"incrementing":true,
"exists":true
}
}
$user = User::find(483);
Output: empty
For your specific query, you can modify it as the following code to make it work:
$user = User::where('mobile_number', '=', Request::get('mobile_number'))
->orwhere('email_id', '=', Request::get('email_id'))
->first()
Upvotes: 4