【问题标题】:Laravel routes condition based on which path, how to get the right pathLaravel 根据哪个路径路由条件,如何获得正确的路径
【发布时间】:2020-02-05 01:40:06
【问题描述】:

我的路线:

不同视图的路线

Route::get('/participants', 'DatatablesController@getIndex')->name('participants');
Route::get('/completed', 'DatatablesController@getIndex')->name('completed');
Route::get('/failed', 'DatatablesController@getIndex')->name('failed');
//route to get data to views
Route::get('participants_dt', 'DatatablesController@getData')->name('get.survey_requests');

控制器:

public function getData()
{
    $request = Request::path();
    error_log($request);
    // $request returns participant_dt currently.
    // I want it to return based on which view I'm on.

    if ($request == 'participants') {
        //return query
    } elseif ($request == 'complete') {
        //return complete
    } else {
        //return failed
    }
}

有没有办法根据它所在的路线命名我的路线?例如如果路由 /complete 被选中,那么路由参与者_dt 将被命名为 complete?

【问题讨论】:

  • 你在哪个视图上是什么意思?你没意见!!视图上的<a href="/participants_dt"></a> 标记与通过localhost:8000/participants_dt 之类的直接URL 访问没有任何区别,您无法分辨出区别

标签: php ajax laravel datatables


【解决方案1】:

由于您的视图位于不同的路由上,您可以使用之前的 URL 来确定请求来自哪个视图

public function getData()
{
    $request = url()->previous(); // Get previous URL
    $request = parse_url($request)['path']; // Remove domain name
    $request = ltrim($request, '/'); // Remove first slash
    error_log($request);
    dd($request); // Returns the route where the view is (ex: participants)
    if ($request == 'participants') {
        //return query
    } elseif ($request == 'complete') {
        //return complete
    } else {
        //return failed
    }
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    理想情况下,您的路由应该转到控制器中的不同方法。例如:

    Route::get('/completed', 'DatatablesController@getCompleted')->name('completed');
    Route::get('/failed', 'DatatablesController@getFailed')->name('failed');
    

    然后在你的控制器中:

    public function getCompleted() {
        $this->getData('completed');
    }
    
    public function getFailed() {
       $this->getData('failed');
    }
    
    protected function getData($status_type = 'participants')
    {
        if ($status_type == 'participants') {
            //return query
        } elseif ($status_type == 'complete') {
            //return complete
        } else {
            //return failed
        }
    }
    

    希望对您有所帮助。

    【讨论】:

    • 我试过了,它从来没有改变 $status_type,只有当 status_type 是参与者时才显示查询。
    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多