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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?