Search code examples
laravelhttpnginxslug

How to append a slug to the end of the url in Laravel 5.3 using eloquent-sluggable package?


I have slug eloquent package. I want to create a url like this: http://www.example.com/houses/id/house-with-2-bedrooms Let me explain the url:

houses and id represents the resource and id as stated by the rest archicture.

the house-with-2-bedrooms segment is the slug itself. the portion that is dynamic is the number 2, representing the number of bedrooms that a house has. So I could have

http://www.example.com/houses/100/house-with-2-bedrooms
http://www.example.com/houses/101/house-with-2-bedrooms
http://www.example.com/houses/102/house-with-3-bedrooms

I know that slug is more often used to create more complex urls, removing url unwanted characters like ~ and ^ but I only want a simple one for now.

I read the tutorial on the Git web site and couldn't make it work neither understand I was doing.

So far I have this:

My House model has a slug field.

I defined the Sluggable trait:

My model:

use Cviebrock\EloquentSluggable\Sluggable;

class House extends Model
{
    use Sluggable; 

       public function announcement()
        {           
             return $this->belongsTo(\App\Announcement::class, 'id' , 'id');  
        }   

   protected $table = 'house';
   protected $primaryKey = 'id';
   protected $fillable = array( 'id', 'capacity', 'bedrooms', 'pool', 'price', 'dir_id', 'identifier', 'photos', 'views', 'active', 'description', 'slug');
   public $timestamps = false;

   protected $connection = 'eloquent_db';

         public function sluggable()
          {
             return ['slug' => ['source' => 'bedrooms'] ];
          }


 }

My controller:

route::resource('houses', HousesController'). 

Solution

  • You can simply achieve that

    On route

    Route::resource('houses', 'HousesController', ['except' => 'show']);
    Route::get('/houses/{id}/{slug}', 'HousesController@show')->name('houses.show');
    

    On view for generating URL

    <a href="{{ route('houses.show', [$house->id, $house->slug]) }}">Sample House</a>