如何定义将参数传递给Laravel中的控制器的速记路由

时间:2017-04-15 21:17:45

标签: laravel syntax routes parameter-passing shorthand

Route::get('/restaurant-detail/{id}', [
// 'as'    => 'restaurant-detail-{id}', // is this legal?
'uses'  => 'RestaurantsController@getRestaurantDetail'
]);

如果这不合法,您如何获得{id}的价值?

1 个答案:

答案 0 :(得分:0)

根据您的评论和您的问题,您需要在博客设置之后使用idslug从数据库中检索帖子。可以使用您定义的路线来实现:

// Routes (web.php)
Route::get('/restaurant-detail/{value}', [
    'as'   => 'restaurant-detail',
    'uses' => 'RestaurantsController@getRestaurantDetail'
]);

此处getRestaurantDetail控制器中的RestaurantsController方法会从您的路由中收到value作为参数,供您在查询中使用:

// RestaurantsController.php
class RestaurantsController extends Controller
{
    ...

    public function getRestaurantDetail($value)
    {
        // First you could check whether you have an id or a slug
        // - Here we'll assume that any string passed is a slug
        $column = is_string($value)? 'slug' : 'id';

        // Now find the post/info using the column
        $post = RestaurantDetail::where($column, $value)->first();

        // Then you can pass your data to a view etc.
        // - Here we simply return it
        return $post;
    }
}