使用 laravel 微风检索登录请求中的关系表

Posted

技术标签:

【中文标题】使用 laravel 微风检索登录请求中的关系表【英文标题】:retrive relation table in login request with laravel breeze 【发布时间】:2022-01-03 15:32:24 【问题描述】:

您好,我想在登录时包含我的关系表角色。我使用 Laravel Breeze 进行身份验证。

模型/用户.php


namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable

    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    //old
    public function bookmarks()
        return $this->hasMany('App\Model\Post','post_bookmarks','user_id','post_id')->get();
        

    public function roles()
        return $this->belongsTo('App\Models\Roles','roles','role_id','id');
    

AuthenticatedSessionController.php


namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthenticatedSessionController extends Controller

    /**
     * Display the login view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    
        return view('auth.login');
    

    /**
     * Handle an incoming authentication request.
     *
     * @param  \App\Http\Requests\Auth\LoginRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(LoginRequest $request)
    
        $request->authenticate();

        $request->session()->regenerate();

        return redirect()->intended(RouteServiceProvider::HOME);
    

    /**
     * Destroy an authenticated session.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    

LoginRequest.php


namespace App\Http\Requests\Auth;

use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class LoginRequest extends FormRequest

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    
        return true;
    

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    
        return [
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ];
    

    /**
     * Attempt to authenticate the request's credentials.
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function authenticate()
    
        $this->ensureIsNotRateLimited();

        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) 
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'email' => __('auth.failed'),
            ]);
        

        RateLimiter::clear($this->throttleKey());
    

    /**
     * Ensure the login request is not rate limited.
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function ensureIsNotRateLimited()
    
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) 
            return;
        

        event(new Lockout($this));

        $seconds = RateLimiter::availableIn($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    

    /**
     * Get the rate limiting throttle key for the request.
     *
     * @return string
     */
    public function throttleKey()
    
        return Str::lower($this->input('email')).'|'.$this->ip();
    

我使用 Laravel-breeze 进行身份验证。一切正常,但我想在用户登录时添加角色名称。如您所见,我也使用了关系,但我很困惑在哪里可以编写代码来获取我的关系表。这是我的代码,谁能告诉我该怎么做?

例如。 登录邮箱:poojan@gmail.com role_id = 1

在角色表中 id: 1, role_name = "Wholseler"

所以当我当前登录时,我正在获取用户数据,但我也想要角色表数据。

提前致谢

【问题讨论】:

所以你想将角色附加到用户权限?? 不,我已经为所有用户分配了角色,但是当用户登录时我也想检索角色名称。 所以你需要根据角色进行重定向吗?? 您提供的所有代码都已内置到框架中。你能告诉我到目前为止你尝试了什么 当我登录时,我也想要用户数据透视表数据,如您在示例中所见。 【参考方案1】:

你可以在你的用户模型中使用属性

protected $appends = ['role_name'];

public function getRoleNameAttribute()

    return $this->roles->first()->role_name ?? 'N/A';

使用上面的代码,您将在用户实例中获得 role_name 属性

如果您希望角色数据与用户数据的关系,请在用户模型中尝试此操作

protected $with = ['roles'];

【讨论】:

很好,它正在工作。我使用受保护的 $with = ['roles'];角色表的所有数据。太感谢了。我可以在 $with 中添加更多表吗,例如 $with = ['roles','products']; ? 是的,你可以添加多个表格

以上是关于使用 laravel 微风检索登录请求中的关系表的主要内容,如果未能解决你的问题,请参考以下文章

JWT 从 Laravel 中的令牌中检索经过身份验证的用户

如何从没有关系laravel 8的另一个表中检索具有多行的行数据

Laravel 5.4:无法从关系中检索数据

从 Laravel 中的关系中检索关系

如何在 Laravel 中使用 eloquent 检索每个用户的特定数据

Laravel 加入以检索总数