php - Laravel 5.2 包 : Auth methods fail in constructor of controller

标签 php laravel-5 laravel-middleware

我已经为我的包添加了一个 Controller ,我需要在该 Controller 的构造函数中调用 Auth 方法,但出现以下错误:

ReflectionException in Container.php line 734: Class hash does not exist

这是我的代码:

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
    }
}

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

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

最佳答案

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

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 
    }
}

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

关于php - Laravel 5.2 包 : Auth methods fail in constructor of controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38418985/

相关文章:

php - Laravel 5.1 SSH - 无法连接到远程服务器

php - laravel VerifyCsrfToken 使用通配符排除 url?

php - 逗号分隔的字符串作为字段和数据 - 在 php mysql 中更新查询

javascript - Yii Cgridview $.fn.yiiGridView.getSelection 函数不能立即工作

php - laravel Eloquent 查询 orWhere

Laravel:如何在模型属性转换上设置日期格式?

php - 从模型中获取所有在数据透视表 Laravel 5 中没有条目的记录

php - 如何将数组参数传递给laravel中的中间件

php - laravel authorizeResource 总是拒绝访问

php - 如何使用 php 从 HTML 中删除 <p> 标签及其内容