Prabesh Prabesh - 6 months ago 50
PHP Question

Laravel 5 - Slug implementation

I am hitting a roadblock with slug and so seeking your expert advice.

We have a drivers table, cars table, fleet-owners table.

- drivers have cars

- fleet owners have drivers who have cars
I am trying to create slug as follows:

www.example.com/drivers/driver-name
www.example.com/cars/car-name
www.example.com/fleet-owners/fleet-owner-name


In my webapp, I implemented the slug using eloquent-sluggable as following with respective the trait.

In the driver model I have create a sluggable method as below

protected $sluggable = [
'build_from' => 'user.name',
'save_to' => 'slug',
];


For drivers, it uses user.name and saves the respective slug and it works as expected for both drivers and cards.

But for fleet owners, I am not able to do this, since for a fleet owner, the driver's name is stored as driver name but I am not able to reference this name or create slug for this.

Answer

I haven't used Eloquent Sluggable and am not sure if I understand your database schema, but possibly something like this could work, assuming the Fleet Owner model Has One/Belongs To a Driver model instance.

public function getNameAttribute()
{
    return $this->driver->name;
}

Then the Fleet Owner model would have a name attribute that Sluggable could make use of:

protected $sluggable = [
        'build_from' => 'name',
        'save_to'    => 'slug',
    ];

You'll have to make sure there is a slug column on your fleet owner table for this to work.