【问题标题】:Laravel 5.2 Package : Auth methods fail in constructor of controllerLaravel 5.2 包:Auth 方法在控制器的构造函数中失败
【发布时间】:2016-11-20 00:20:31
【问题描述】:

我为我的包添加了一个控制器,我需要在这个控制器的构造函数中调用 Auth 方法,但我收到以下错误:

Container.php 第 734 行中的反射异常: 类哈希不存在

这是我的代码:

use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;

class CartController extends Controller
{
    private $customer;

    public function __construct()
    {
         $this->middleware('auth', ['except' => ['add']]);
         $multiauth = config('cart.multiauth');
         if ($multiauth) {
             $guard       = config('auth.defaults.guard');
             $this->customer = Auth::guard($guard)->user();
         } else {
             $this->customer = Auth::user();
         }
    }

    public function add()
    {
        // Code
    }
}

当我在其他函数中添加构造函数的代码时,它可以正常工作,但是从控制器的构造函数中调用它时会失败。

我已经搜索了很多,但没有找到可行的解决方案。

【问题讨论】:

  • 你做过composer dump-autoload吗?
  • hash 类是否由您定义或实现?你有定制的后卫吗? hash 类应该被称为Hash 吗?请注意,有些操作系统区分大小写,而有些则不区分大小写!
  • 是的,我已经运行了'composer dump-autoload'
  • 不,我没有定义哈希类,它是laravel的默认哈希类。
  • 您似乎从配置文件auth.defaults.guard 中获取保护配置。检查其中是否出现hash这个词,并尝试将其更改为Hash(大写H)。

标签: php laravel-5 laravel-middleware


【解决方案1】:

我通过添加中间件解决了这个问题:

namespace myNamespace\myPackage;

use Closure;
use Illuminate\Support\Facades\Auth;

class CustomerMiddleware
{
     public function handle($request, Closure $next)
     {
         $multiauth = config('cart.multiauth');
         if ($multiauth) {
             $guard   = config('auth.defaults.guard');
             $customer = Auth::guard($guard)->user();
         } else {
             $customer = Auth::user();
         }

         $request->attributes->add(['customer' => $customer]);

         return $next($request);
     }
}

然后我将这个中间件用于“购物车/添加”路线:

Route::group(['middleware' => ['web']], function () {
    Route::group(['middleware' => 'customer'], function() {
        Route::post('cart/add',
                    'myNamespace\myPackage\CartController@add');
    });
});

所以通过检查 'CartController' 的 'add' 方法中的 $request->get('customer') 参数,我可以访问当前用户的信息:

class CartController extends Controller
{
    public function __construct() { }

    public function add()
    {
       $customer = $request->get('customer');
       // Code 
    }
}

我希望这对其他人有帮助:)

【讨论】:

    【解决方案2】:

    你不能在控制器 __construct 中使用中间件,创建一个函数并使用它

    【讨论】:

    • 感谢您的回答。但我需要在运行“添加”方法之前执行此代码。通过定义另一个函数,我应该在“add”方法中调用该函数,以便将客户变量设置为 null,因为“add”方法不使用“auth”中间件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2017-11-10
    • 2017-01-03
    • 1970-01-01
    • 2016-09-27
    • 2016-06-20
    相关资源
    最近更新 更多