How can I use Null coalescing ?? operator of PHP inside of an if statement with Laravel Eloquents to check an object exists or not? Currently, it is showing this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.categories_id' in 'where clause' (SQL: select * from
posts
whereposts
.categories_id
= 2 andposts
.categories_id
is not null andposts
.deleted_at
is null)
I tried to delete category freely when that category is not associated with a post. if it's associated with a post, only then it should show the error message
public function destroy(Categories $category)
{
if ($category->posts ?? 0) {
if ($category->posts->count() > 0 ?? 0) {
session()->flash('warning', 'Category have related post. Can\'t be deleted!');
return redirect()->back();
}
}
$category->delete();
session()->flash('success', 'Category deleted successfully!');
return redirect(route('categories.index'));
}
By the way, I have these relationships right now:
App\Post.php Model
public function category()
{
return $this->belongsTo(Categories::class);
}
App\Categories.php Model
public function posts()
{
return $this->hasMany(Post::class);
}
It's working if I remove $category->post
from my if condition. But then it deletes all types of categories including those associated with posts.
Note: isset($category->post)
also given error.
Please help me if you can. Thanks.