No query results for model [App\Posts] Error Hi guys,
Hi, am facing an error like below when I trying to delete my post category. Can someone help me to resolve this?
Error
No query results for model [App\Posts]
function
public function delete(Request $request)
{
$posts = Posts::where('cat_id', $request->cat_id)->get();
if (count($posts) != 0){
foreach ($posts as $post){
$postdata = Posts::find($post->id);
dd($postdata);
$postdata->delete();
}
}
$subCats = Subcategory::where('cat_id', $request->cat_id)->get();
if (count($subCats) > 0){
foreach ($subCats as $subCat){
$subCatData = Posts::findOrFail($subCat->id);
$subCatData->delete();
}
}
$data = Category::findOrFail($request->cat_id);
$data->delete();
return back()->with('status', 'Category successfully deleted.');
}
Please, can anyone help me with this?
->get() will return a collection and therefore you can use all the collection methods:
https://laravel.com/docs/6.x/collections#available-methods
So, you can do $posts->count() instead of using count($posts)
You then loop through each $post, which is an instance of the Post model, so you do not need to find it again, you can work directly with the $post.
$posts = Posts::where('cat_id', $request->cat_id)->get();
if ($post->count() != 0){
foreach ($posts as $post){
dd($post);
$post->delete();
}
}
It also looks like you are deleting the same post in the second loop. Which line is it failing on?
Is your first line Posts::where(...) typo error? the model is App\Post or App\Posts ???
one other thing to note is that you are not deleting posts relating to Subcategories? but you are deleting them?
if you use Mysql Foreign key constraints they may do the work for you i think?
All of you, who is the reply. Thanks. I solved it with @glenuk answer. Thanks again.
This first part can be reduced;
Posts::where('cat_id', $request->cat_id)->delete();
You can do similar to the others
but your model should be called Post not Posts (by convention)
and your error does not seem related to this function. Perhaps the error occurs after you return back(). But it would be more use to know the entire error.
Please sign in or create an account to participate in this conversation.