You can use the implicit model binding for routes with custom keys like this:
use App\Models\CategoryService as Category;
use App\Models\Service;
Route::get('/{category:slug}/{service:slug}', function (Category $category, Service $service) {
/* ... */
});
You have to make sure that the name of the route-bind is the same as the parameter name in the closure.
Hi ! I'm a fresh Laravel coder and I work with livewire
Here is my component :
`<?php
namespace App\Http\Livewire;
use App\Models\Service;
use App\Models\ServiceCategory;
use Livewire\Component;
class ServiceDetailsComponent extends Component
{
public $service_slug;
public function mount($service_slug)
{
$this->service_slug = $service_slug;
}
public function render()
{
$service = Service::where('slug', $this->service_slug)->first();
$r_service = Service::where('service_category_id', $service->service_category_id)->where('slug', '!=', $this->service_slug)->inRandomOrder()->first();
return view('livewire.service-details-component', ['service' => $service, 'r_service' => $r_service, 'cat' => $cat])->layout('layouts.base');
}
}`
And route :
`<?php
Route::get('/service/{service_slug}', ServiceDetailsComponent::class)->name('home.service_details');`
Well you can definitely get what you want a bit easier using because Livewire supports the Laravel way of route model binding. I would highly recommend you check out the Laravel and Laravel-Livewire documentation to learn about all this. First, configure your route like this:
<?php
Route::get('/service/{service:slug}', ServiceDetailsComponent::class)
->name('home.service_details');
Then you can just type-hint your Model in your mount
function like this:
<?php
// ServiceDetailComponent.php
namespace App\Http\Livewire;
use App\Models\Service;
use App\Models\ServiceCategory;
use Livewire\Component;
class ServiceDetailsComponent extends Component
{
public Service $service;
public Service $related;
public ServiceCategory $category;
public function mount(Service $service)
{
$this->service = $service;
$this->related = Service::where('id', '<>', $service->id)
->where('service_category_id', $this->category->id)
->inRandomOrder()
->first();
$this->category = $service->category;
}
public function render()
{
return view('livewire.service-details-component')->extends('layouts.app');
}
}
In your view you will now have access to all the public properties of your component like this:
<div>
My service: {{ $service->slug }} <br />
My related service: {{ $related->slug }} <br />
My category: {{ $category->name }}
</div>
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community