【问题标题】:Laravel pass exact parameter to routeLaravel 将确切的参数传递给路由
【发布时间】:2016-11-22 12:45:49
【问题描述】:

我已经翻译了需要重定向到特定控制器功能的 url,但我还需要传递一个确切的参数。

例如,我想显示所有足球新闻,但在 url 中我没有体育足球的 ID (id=1),所以我需要将参数 id=1 传递给 index() 函数。

Route::get('/football-news/', ['as' => 'news.index', 'uses' => 'NewsController@index']);

将“足球”作为参数传递不是一个选项,因为它只是一个示例。真正的路由被翻译了,代码如下:

Route::get(LaravelLocalization::transRoute('routes.football.news'), ['as' => 'news.index', 'uses' => 'NewsController@index']);

【问题讨论】:

    标签: laravel routing localization


    【解决方案1】:

    假设你有一个 NewsController 来获取所有的新闻,比如

    class NewsController extends Controller
    {
     public function index()
     {
      $news = News::all(); //you have to create News model
      return view('news.index', compact('news')); //use to pass data in view
     }
    
    public function show($id)
     {
        $news_detail=News::find($id); //to fetch detail of news from database
    
        return view('news.show', compact('news_detail'));
     }
    }
    

    在views/news 文件夹中创建index.php 和show.php。在 index.php 中

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

    这里使用“/news/{{$news_item->id}}”可以将特定新闻的 id 传递到路由文件中。 在show.php中

    <h1>news</h1>
    <h1>
    {{ $news_detail->title }}
    </h1>
    <ul class="list-group">
    @foreach($news_detail->detail as $details)
       <li class="list-group-item">{{$details}}</li>
    @endforeach
    </ul>
    

    在路由文件中

    Route::get('/news/{news}', 'NewsController@show');
    

    现在你必须在 NewsController.php 中创建 show($id) 函数,它的参数是 id。

    【讨论】:

      【解决方案2】:

      您可以使用 ?id=1 参数(例如 domain.com?id=1)附加索引 URL,并使用 Request::get('id'); 在您的索引控制器操作中获取它

      例如:

      模板文件中的网址:

      <a href="domain.com?id=1" />
      

      在您的 NewsController 中:

      public function index(Request $request){
          $id = $request->get('id');
      }
      

      即使您没有在路由文件中指定通配符,您也应该能够访问该参数。


      编辑: 您将不得不为不同的路线调用不同的@action。你可以传入一个 id 通配符。 例如,在 Route 文件中:

      Route::get('tennis-news/{id}', 'NewsController@tennisIndex');
      Route::get('football-news/{id}', 'NewsController@footballIndex');
      

      那么在NewsController中你必须有公共方法tennisIndex($id)footballIindex($id),这些方法可以访问你在路由中设置的通配符。

      例如,在 NewsController 中

      public function tennisIndex($id){
          $tennnis_news = News::where('sport'='tennis)->where('id', $id)->get();
          return view('tennis_news', compact('tennnis_news'));
      }
      

      【讨论】:

      • 但是可以告诉 routes.php 在 URL /football-news/ 的情况下它应该使用 NewsController@index(1),如果 /tennis-news/ 它应该使用 index( 2)等等?
      猜你喜欢
      • 2019-03-03
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 2018-06-20
      • 2015-10-15
      • 2015-01-25
      相关资源
      最近更新 更多