Home > Enterprise >  Laravel Friendly url instead of ID
Laravel Friendly url instead of ID

Time:10-21

OK all I am so lost. The following prints our [] an empty array. This is really messing me up. AppServiceProvider to populate the dropdown

\View::composer(['layouts/frontend/partials/header'], function ($view) { $title = Weekend::all('title','id'); $view->with(['title'=>$title]); });

route Route::get('weekends/{weekend:title}',[PagesController::class,'getCurrent']);`

Link to the individual page

 @foreach($title as $title) <li><a href="weekends/{{$title->title}}">{{$title->title}}</a></li> @endforeach``` controller ``` public function getCurrent(Weekend $title) { return $title; }

And the Model

<?php

namespace App\Models\Webmaster;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Weekend extends Model
{
    use HasFactory;
    protected $fillable = [];


    public function weekendTeamMembers() {
        return $this->hasMany(App\Models\Webmaster\WeekendTeamMember::class);
    }

    public function getRouteKeyName() {
        return 'title';
    }


}

enter code here

I have everything working but I would like to have the url passing the weekend title instead of ID. Not sure how to do this. In my AppService Provider I have the following to populate the navbar dropdown with titles:

\View::composer(['layouts/frontend/partials/header'], function ($view) {
    $title = Weekend::all('title', 'id');

    $view->with(['title'=>$title]);
});

My route for each individual page is

Route::get('weekends/{weekend}', [PagesController::class, 'getCurrent']);

The Link is

@foreach ($title as $title)
    <li><a href="{{ $title->id }}">{{ $title->title }}</a></li>
@endforeach

But if I change {{ $title->id }} to {{ $title->title }} I get 404.

And the controller is

public function getCurrent(Weekend $weekend)
{
    return view('pages.weekend')->with(['weekend'=> $weekend]);
}

CodePudding user response:

you can do just like that

Route::get('weekends/{weekend:title}',[PagesController::class,'getCurrent']);

CodePudding user response:

There are several ways to approach changing the route binding key (which is set to the primary key by default). The easiest way is to add it to your implicit route binding (add :title):

Route::get('weekends/{weekend:title}',[PagesController::class,'getCurrent']);

Another way to do it is by updating your model to change the default:

public function getRouteKeyName() {
    return 'title';
}

You can find more documentation on changing the key in the Laravel docs.

  • Related