phplaravellaravel-11

Show Trashed Items in Laravel


I have many products in my categories and I can get all of the products based on the category successfully. But, when I tried to get the trashed Categories (I used soft delete both in the categories and products), it gave me an error

Call to a member function products() on null

I've tried to use a different function name, but the error still occurs.

Models

// CategoryModel
public function products()
{
    return $this->hasMany(Product::class, 'category_id','id');
}
// ProductModel
public function category()
{
    return $this->belongsTo(Categories::class, 'category_id','id')->withTrashed();
}

Controllers

// IndexController
public function productByCategory($name)
{
    $categories = Categories::where('name', $name)->first();
    $productsCategories = $categories->products()->get(); // the error occurs here 
    return view('products-category', compact('productsCategories','categories'));
}
// CategoryController
public function trash()
{
    $categories = Categories::onlyTrashed()->paginate(10);
    return view("categories.trash", compact('categories'));
}
// ProductController
public function trash()
{
    $products = Product::onlyTrashed()->paginate(10);
    return view("products.trash", compact('products'));
}

Solution

  • After some time, I figured it was because it's read as the same route address. The "trash" is considered as a "name" parameter by Laravel. I solved it by changing the route address