Laravel:独特的URL&每条记录的个人资料

时间:2018-06-02 16:40:18

标签: php laravel

目前,我有一张包含律师名单的表格,例如。我可以按路线/网络显示各州的律师名单:

// Lawyers per state

Route::get('/lawyers/{state}', function ($state) {
$states = DB::table('states')->get();
$lawyers = DB::table('lawyers')->join('states', 'states.abbr', '=', 'lawyers.state')
                                       ->where('states.abbr', '=', $state)
                                       ->orderBy('lawyers.featured', 'desc')
                                       ->get(['lawyers.*', 'states.name AS state_name']);
$statename = DB::table('states')->where('abbr', $state)->value('name');
return view('pages.lawyers', ['lawyers' => $lawyers, 'states' => $states, 'statename' => $statename]);
});

这正确显示了律师名单。

我想要的是为每位律师创建一个唯一的网址,例如带有网址结构/lawyers/{state}/{firstname}-{lastname}-{zipcode}的个人资料页面视图,因此点击列表中的姓名会转到律师档案。

完成此任务的正确方法是:

  1. 律师网址显示lawyers.profile视图
  2. 列表中的律师名称链接到正确的网址
  3. 谢谢!

2 个答案:

答案 0 :(得分:1)

只需添加更多路线参数,就像您为{state}所做的那样:

Route::get('/lawyers/{state}/{firstname}-{lastname}-{zipcode}', function ($state, $firstname, $lastname, $zipcode) {
    // Logic
});

答案 1 :(得分:1)

在web.php中你可以做到。还在$ min内使用缓存执行一次db查询

$minutes = 10;
$lawyers = \Illuminate\Support\Facades\Cache::remember('', $minutes, function () {
    return DB::table('lawyer')->get([
        'firstname',
        'lastname',
        'zipcode',
        'state',
    ]);
});

foreach ($lawyers as $lawyer) {
    $url  = sprintf('/%s/%s-%s-%s', $lawyer->state, $lawyer->firstname, $lawyer->lastname, $lawyer->zipcode);
    Route::get($url, 'your action');
}