retrive relation table in login request with laravel breeze

  authentication, laravel, laravel-8, laravel-breeze

Hello I want to include my relation table roles when I login. I used Laravel Breeze for authentication.

Models/User.php


namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

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('AppModelPost','post_bookmarks','user_id','post_id')->get();
    }    

    public function roles(){
        return $this->belongsTo('AppModelsRoles','roles','role_id','id');
    }
}

AuthenticatedSessionController.php


namespace AppHttpControllersAuth;

use AppHttpControllersController;
use AppHttpRequestsAuthLoginRequest;
use AppProvidersRouteServiceProvider;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     *
     * @return IlluminateViewView
     */
    public function create()
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     *
     * @param  AppHttpRequestsAuthLoginRequest  $request
     * @return IlluminateHttpRedirectResponse
     */
    public function store(LoginRequest $request)
    {
        $request->authenticate();

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

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

    /**
     * Destroy an authenticated session.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpRedirectResponse
     */
    public function destroy(Request $request)
    {
        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}

LoginRequest.php


namespace AppHttpRequestsAuth;

use IlluminateAuthEventsLockout;
use IlluminateFoundationHttpFormRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesRateLimiter;
use IlluminateSupportStr;
use IlluminateValidationValidationException;

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 IlluminateValidationValidationException
     */
    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 IlluminateValidationValidationException
     */
    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();
    }
}

I have used Laravel-breeze for the authentication. It’s all working fine but I want to add Role name also when user gets login. As you can see I have also used relationship but I’m confused where can I write the code to get my relation table. This is my code, Can anyone please tell me how can I do?

Thanks in Advance

Source: Laravel

Leave a Reply