donglang5157 2017-03-10 12:16
浏览 18
已采纳

Laravel:仅将主要实体绑定到我的会话中

Using Laravel 5.4

I have following entities in my app:

Employees, Contractors, Clients.

I have restfull routes for each like so:

/employees/1
/contractors/1
/clients/1
..

I have the need to get the current entity based on the routes, so i did the following in my RouteServiceProvider:

Route::bind('employee', function ($value) {
    $employee = Employee::findOrFail($value);
    session(['activeEntity' => $employee]);
    return $employee;
});

Route::bind('client', function ($value) {
    $client = Client::findOrFail($value);
    session(['activeEntity' => $client]);
    return $client;
});

Route::bind('contractor', function ($value) {
    $contractor = Contractor::findOrFail($value);
    session(['activeEntity' => $contractor]);
    return $contractor;
});

This works fine for all the top-level routes. But i also have following routes:

/clients/1/employees/1

in this case i would like the activeEntity to be Client, but currently the active entity in the session will be set to Employee

How would i prevent that from happening? And bind the correct entity to the session ?

  • 写回答

1条回答 默认 最新

  • dongyinting3179 2017-03-10 16:48
    关注

    I would suggest to handle it via middleware. You may create SetActiveEntityMiddleware with handle() method like this:

    public function handle($request, Closure $next, $guard = null)
    {
        if ($request->is('employees/*')) {
            $id = $request->route()->parameter('employee');
    
            $employee = Employee::findOrFail($id);
    
            session(['activeEntity' => $employee]);
        }
    
        if ($request->is('clients/*')) {
            $id = $request->route()->parameter('client');
    
            $client = Client::findOrFail($id);
    
            session(['activeEntity' => $client]);
        }
    
        if ($request->is('contractors/*')) {
            $id = $request->route()->parameter('contractor');
    
            $contractor = Contractor::findOrFail($id);
    
            session(['activeEntity' => $contractor]);
        }
    
        return $next($request);
    }
    

    Here is Laravel Middleware Docs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算