Reputation: 3307
I'm working on a little rest API,and in my controller a json
response works only if the $object->exists()
returns 1
but for any other cases it sends errors
Here is my code :
public function show($id)
{
$category=Category::find($id);
return response()->json(
($category->exists()?$category:["message"=>"not found"])
);
}
When the category is found i get row back in a json format
and it doesn't work for the false
case.
What i wanted to do first was that in a case of an error
to return message and code 404 code status
like the following code:
public function show($id)
{
$category=Category::find($id);
return response()->json(
($category->exists()?$category:(["message"=>"not found"],404))
);
}
But nothing worked either while my code seems well written and i'm getting the exact same problem with the destroy method:
public function destroy($id)
{
$category=Category::find($id);
if($category->exists()){
$category->delete();
return response()->json(array("message"="category deleted","success"=>true));
}
return response()->json(array("message"=>"Not found"),404);
}
Upvotes: 0
Views: 1275
Reputation: 5552
What i wanted to do first was that in a case of an error to return message and code 404 code status like the following code
The findOrFail()
method exists for exactly this case:
public function show($id)
{
$category = Category::findOrFail($id);
return $category;
}
In the event that no model was found, findOrFail()
will throw a ModelNotFoundException which causes a 404 to be returned.
Upvotes: 1
Reputation: 775
exists()
is a builder method and you are executing it on a model instance.
As you are already fetching the model instance from the database so you can instead check if it is empty or not. You can do something like:
empty($category) ? ["message"=>"not found"] : $category
Upvotes: 0
Reputation: 33186
Using Category::find($id);
will return a Category
object when the record actually exists in the database. However, if the record does not exist, it will return null
. Because of this, you are trying to call the function exists()
on null
which is not possible.
It's better to check if the variable has the value null
or use a null coalescing operator if you are on php7.
$category = Category::find($id);
return response()->json(
$category ?? ["message" => "not found"],
404
);
Upvotes: 4