What is your expected output? You are indeed fetching for the specific category in the controller, but you're doing nothing with it..
Apr 20, 2022
2
Level 1
product categories
Hey! I am creating an ecommerce website in Laravel and my categories are not displaying correctly. There's just the list of the categories and when clicking on one of them, the url is changing depending on the slug but that's all, it is still displaying just the list.
Category Controller
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function createCategory(Request $request)
{
$categories = Category::where('parent_id', null)->orderby('name', 'asc')->get();
if($request->method()=='GET')
{
return view('create-category', compact('categories'));
}
if($request->method()=='POST')
{
$validator = $request->validate([
'name' => 'required',
'slug' => 'required|unique:categories',
'parent_id' => 'nullable|numeric'
]);
Category::create([
'name' => $request->name,
'slug' => $request->slug,
'parent_id' =>$request->parent_id
]);
return redirect()->back()->with('success', 'Category has been created successfully.');
}
}
public function input($slug) {
$categories=Category::all();
$category=Category::where($slug=$this->slug)->first();
$category_id=$category->id;
$category_name=$category->name;
$products=Product::where('category_id',$category_id);
return view('categories',
['categories' => $categories, 'products'=>$products]);
}
public $slug;
public $categories;
}
Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['name', 'slug', 'parent_id'];
public function subcategory()
{
return $this->hasMany(\App\Models\Category::class, 'parent_id');
}
public function parent()
{
return $this->belongsTo(\App\Models\Category::class, 'parent_id');
}
}
web.php
Route::any('category/create', [CategoryController::class, 'createCategory'])->name('createCategory');
Route::get('/categories/{slug}', [CategoryController::class, 'input'])->name('inputCategory');
categories.blade.php
@foreach($categories as $category)
<li><a href="{{ route('inputCategory',['slug'=>$category->slug])}}">{{ $category->name }}</a></li>
@endforeach
categories table contains id, name, slug, parent_id products table contains id, category_id, name, price, description, image
Please or to participate in this conversation.