Search code examples
laravellaravel-livewire

Can I pass a parameter from URL to Livewire Laravel?


I am new to Laravel Livewire. I want to be able to use the parameter passed from the URL in the Laravel livewire blade file. I have been able to access the parameter in the controller from the route, performed the logic and pass it to the component blade view file, but I am a bit confused how to pass or access the object passed to the component view file in the livewire view file where the display logic is located.

I have the major files and codes involved in this scenario:

routes/web.php

Route::get('/productcategory/{category}', [App\Http\Controllers\CategoryController::class, 'productCategory'])->name('productcategory');

App/HTTP/controller/CategoryController.php

public function productCategory($category)
    {
        $cat = str_replace("+"," ",$category);
        $categories = Categories::all();
        $products= Product::where('category', $cat)->paginate(10);
        return view('components.productcategories', compact('categories','products'));
    }

resources/view/component/productcategories.blade.php

@extends('layouts.newapp')

@section('title','Product Category')
@section('content')
<div>
    @include('inc.header')

    @livewire('category')
   
    @include('inc.footer')
</div>
@endsection

App/HTTP/livewire/Productcategory.php

public function render()
    {
        return view('livewire.category');
    }

resources/view/livewire/category.blade.php

@if (!empty($products))
  @foreach ($products as $item)
     <p>{{ $item->name}}</p>
  @endforeach
@endif

Please I need help with this.


Solution

  • You can pass it in the @livewire() directive like just make sure that the $product is declared to your livewire component class:

    Blade Component

    @livewire('category', [
        'products' => $products,
    ])
    
    

    Livewire Class

    class Productcategory
    {
        public $products
    
        public function render()
        {
            return view('livewire.category');
        }
    }