如何在Laravel 5.4中使用slug制作url?

时间:2017-07-01 20:35:49

标签: php laravel web laravel-5.4

现在我正在尝试用slug做一个Laravel网址。我有我的主页,我显示所有类别:

<div class="panel-body">
      @foreach($categories as $category)
            <p><a href="{{ URL::to('test/' . $category->slug) }}">{{ $category->name }}</a></p>
      @endforeach
</div>

现在我想去某个类别页面。我创建了路线:

Route::get('/test', 'FuelAccountingController@index')->name('fuel_accounting');
Route::get('/test/{slug}', 'FuelAccountingController@element');

控制器中的功能:

public function index()
{
    $categories = DB::table('fuel_accounting_categories')
        ->select('id', 'name', 'slug')
        ->get();

    return view('pages.fuel_accounting')->with('categories', $categories);
}

public function element($slug)
{
    $category = DB::table('fuel_accounting_categories')
        ->select('slug')
        ->where('slug', '=', $slug)
        ->first();

    return view('pages.fuel_accounting_element')->with('category', $category);
}

当我尝试访问某个页面时(例如:laravel.dev/test/current_category),它无效。有人能解释我怎么做吗?

错误:抱歉,找不到您要查找的页面。 (1/1)NotFoundHttpException

固定

1 个答案:

答案 0 :(得分:0)

<div class="panel-body">
      @foreach($categories as $category)
            <p><a href="{{URL::to('test/'.$category->name)}}">{{ $category->name }}</a></p>
      @endforeach
</div>