Auth:user()在多重身份验证应用程序中返回NULL

时间:2019-01-28 21:01:32

标签: php laravel authentication

我正在使用Laravel 5.7中的一个多义化应用程序。目前,我有两种用户(用户和商店),但是在与商店合作时,我无法在刀片布局中显示用户名。我收到此错误消息:“试图获取非对象的属性'名称'”

我已经确定我正在与一家老字号商店合作。我使用刀片指令来显示某些商店菜单的选项,当我使用auth('shop')-> user()-> name而不是Auth :: user()-> name时,它也可以工作。

我的代码:

创建新商店的RegisterController类:

<?php
namespace App\Http\Controllers\Shop\Auth;

use App\Model\Shop\Shop;
use App\Model\Shop\ShopType;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;

class RegisterController extends Controller
{



use RegistersUsers;
/**
 * Where to redirect users after registration.
 *
 * @var string
 */
protected $redirectTo = '/shop/typeSelection';
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest:shop');
}
/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'cif' => ['required', 'max:9', 'unique:shops'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:shops'],
        'password' => ['required', 'string', 'min:6', 'confirmed'],
        'accept_conditions' => ['required'],
    ]);
}
/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\Model\Shop\Shop
 */
protected function create(array $data)
{
    $shopType = ShopType::where("description","=",'Free')->select("id") -> first() -> id;

    return Shop::create([
        'name' => $data['name'],
        'cif'   => $data['cif'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'active' => false,
        'activation_code' => $data['activation_code'],
        'shop_type' => $shopType, //Siempre la creamos como free pero inactiva.
    ]);
}
/**
 * Handle a registration request for the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $this->validator($request->all())->validate();

    $request['activation_code'] = str_random(30).time();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return $this->registered($request, $user)
        ?: redirect($this->redirectPath());

}
/**
 * Get the guard to be used during authentication.
 *
 * @return \Illuminate\Contracts\Auth\StatefulGuard
 */
protected function guard()
{
    return Auth::guard('shop');
}
}

模型店:

<?php

namespace App\Model\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Shop extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'cif', 'email', 'password', 'activation_code', 'active', 'shop_type'
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * Atributos boleanos para que se haga la conversion de 0 y 1 a bool.
 *
 * @var array
 */
protected $casts = [
    "active" => "boolean",
];

/**
 * Relacion de Eloquent
 *
 */
public function shopType()
{
    return $this->belongsTo(ShopType::class);
}

/**
 * Para saber el tipo de usuario autenticado
 *
 *
 * @return boolean
 */
public function isUser()
{
    return false;
}

/**
 * Para saber el tipo de usuario autenticado
 *
 *
 * @return boolean
 */
public function isShop()
{
    return true;
}

/**
 * Para saber el tipo de usuario autenticado
 *
 *
 * @return boolean
 */
public function isAdmin()
{
    return false;
}
}

Config / Auth.php保护线:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    'shop' => [
        'driver' => 'session',
        'provider' => 'shops',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
    'shops' =>[
        'driver' => 'eloquent',
        'model' => App\Model\Shop\Shop::class,
    ],
], 

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],

    'shops' => [
        'provider' => 'shops',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

布局的俯视图(仅主体):

<body>
<div class="app ">
    <nav class="navbar navbar-light bg-light justify-content-between">
        <div class="container-fluid">
            <div class="col-md-2">
                <a class="navbar-brand" href="{{ url('/') }}">
                    <img src="{{asset('img/logo/logo_75x100.png')}}" alt="{{ __('app/navbar.altLogo') }}">
                </a>
            </div>
            <div class="col-md-6">
                <div class="input-group md-form form-sm form-2 pl-0">
                    <input class="form-control my-0 py-1 amber-border" type="text" placeholder="{{ __('app/navbar.searchText') }}" aria-label="Search">
                    <div class="input-group-append">
                        <span class="input-group-text amber lighten-3" id="basic-text1"><i class="fas fa-search ic-navbar" aria-hidden="true"></i></span>
                    </div>
                </div>
            </div>
            @logued
                <div class="col-md-1">
                    <a href="#">
                        <i class="fas fa-user mr-sm-1 ic-navbar">&nbsp;{{Auth::user()->name }}</i>
                    </a>
                </div>
                <div class="col-md-1">
                    <a href="{{ route('logout') }}"
                       onclick="event.preventDefault();
                                                 document.getElementById('logout-form').submit();">
                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                            @csrf
                        </form>
                        <i class="fas fa-sign-out-alt mr-sm-1 ic-navbar">&nbsp;Logout</i>
                    </a>
                </div>
            @else
            <div class="col-md-1">
                <a href="{{ route('login') }}">
                    <i class="fas fa-sign-in-alt  mr-sm-1 ic-navbar" aria-hidden="true">
                        &nbsp;Login
                    </i>
                </a>
            </div>
            <div class="col-md-1">
                <a href="{{ route('register') }}">
                    <i class="fas fa-user-plus  mr-sm-1 ic-navbar">&nbsp;Register</i>
                </a>
            </div>

            @endlogued


            <div class="col-md-1">
                <i class="fas fa-shopping-cart  mr-sm-1 ic-navbar">&nbsp;Cart</i>
            </div>
            <div class="col-md-1">
                <i class="fas fa-globe  mr-sm-1 ic-navbar">&nbsp;Lang</i>
            </div>



        </div>
    </nav>

    @auth
        <p>Soy autorizado</p>
    @elseauth
        <p>No soy autorizado</p>
    @endauth

    @guest
        <p>soy invitado</p>
    @elseguest
        <p>No soy invitado</p>
    @endguest

    <main class="py-4">
        @yield('content')
    </main>
</div>
</body>

我希望手表店的用户名而不是收到错误消息。就像我说的,我使用auth('shop')-> user()-> name而不是Auth :: user()-> name获得预期的结果。几个月前,我还在一个类似的项目中工作,这个问题没有发生,并检查了我是否具有相同的代码。

2 个答案:

答案 0 :(得分:1)

我不能确定不检查您的旧项目。但是,由于多重身份验证,可能会出现此问题。默认情况下,Auth :: user()检查“网络”防护。但是当您以“商店”门卫登录时;用户函数返回NULL。

优良作法是明确定义防护。您可以按照此讨论了解更多tips

答案 1 :(得分:0)

我再次检查了我的旧项目,并且正在使用Auth :: user(),它正在对三种不同的身份验证进行工作。 我想记住我是如何做到的,但是这很困难,这是我的第一个Laravel项目,我测试了我在线观看的每个示例...