Reputation: 53
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.
Upvotes: 0
Views: 2662
Reputation: 6349
Aside from the suggestions, you can also use defaults
, ie:
Route::get('/posts/north-america', PostCategory::class)
->defaults('category', 'north-america');
Upvotes: 0
Reputation: 180126
Since you're using route model binding, it'll be automatically provided to the mount
function:
public $category;
public function mount(Category $category)
{
$this->category = $category;
}
In PHP 7.4+, you can skip the mount()
so it's even simpler; just declare the parameter and match the class and variable name from your routes file.
class YourLivewireComponent extends Component
{
public Category $category;
}
If you just wanted to get a random GET parameter, inject the Request class:
public $foo;
public function mount(Request $request)
{
$this->foo = $request->get('foo');
}
(You can inject any dependency this way, not just Request.)
Upvotes: 2
Reputation: 1216
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');
}
}
Upvotes: 1