oluwatyson
oluwatyson

Reputation: 301

How to log in a user with custom guard in Laravel within a controller

I have a custom guard set up for 'customer' which has a LoginController that works absolutely fine. The login controller is as follows:

  public function login(Request $request)
  {
    // Validate form data
    $this->validate($request, [
      'email' => 'required|email',
      'password' => 'required|min:6'
    ]);
    // Attempt to log the user in
    if(Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
    {
      return redirect()->intended(route('customer.dashboard'));
    }
    // if unsuccessful
    return redirect()->back()->withInput($request->only('email','remember'))
  }

Now, within my workflow in another route where I check out customers; I have another controller where I create a new customer. I then attempt to log them in since I have all their details, this doesn't seem to work, does anyone have any idea on what I am doing wrong?

  public function registerCustomer($data)
  {
    $pw = Hash::make($data->pw->main);
    $customer = new Customer;
    $customer->firstname = $data->customer->name;
    $customer->lastname = $data->customer->lastname;
    $customer->mobile = $data->customer->mobile;
    $customer->email = $data->customer->email;
    $customer->password = $pw;
    $customer->save();
    //I HAVE TRIED THIS
    // if(Auth::guard('customer')->attempt(['email' => $data->customer->email, 'password' => $pw]))
    // {
    //   dd('logged in');
    // }
    //AND NOW THIS...
    $logged =  Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $pw ]);
    dd($logged);
  }

Upvotes: 1

Views: 745

Answers (1)

In registerCustomer function, $pw is an encrypted password. You could not use it for Auth::guard('customer'). You have to replace $pw by $data->pw->main.

$logged =  Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $data->pw->main ]);
dd($logged);

Upvotes: 2

Related Questions