【问题标题】:Laravel: unique URL & profile for each recordLaravel:每条记录的唯一 URL 和个人资料
【发布时间】:2018-06-03 01:06:09
【问题描述】:

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

// 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]);
});

这正确显示了律师名单。

我想要为每个律师创建一个唯一的 URL,例如具有 URL 结构 /lawyers/{state}/{firstname}-{lastname}-{zipcode} 的个人资料页面视图,因此在列表中单击他们的姓名会转到律师个人资料。

实现这一点的正确方法是:

  1. 律师网址显示lawyers.profile 视图
  2. 列表中的律师姓名链接到正确的 URL

谢谢!

【问题讨论】:

    标签: php laravel


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      在 web.php 中你可以做到。还使用缓存在 $minutes 期间执行了一次数据库查询

      $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');
      }
      

      【讨论】:

      • 视图将添加到这里以显示每个律师的个人资料视图,例如lawyers.profile?
      • Route::get($url, function () {//你的代码;返回视图('your-view');});
      • 或使用 Controllere Route::get($url, 'YourController@yorMethod'); 见https://laravel.com/docs/5.5/routing#named-routes
      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 2016-04-21
      • 1970-01-01
      • 2014-06-01
      • 2014-07-22
      • 2021-07-10
      • 1970-01-01
      • 2016-09-01
      相关资源
      最近更新 更多