Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Different way to authentication in laravel

Authentication Using Auth attempt

If your password is stored in the database using the bcrypt hashing algorithm, and you want to authenticate users by comparing the hashed password, you can follow Laravel's built-in authentication features. Laravel provides a convenient Auth facade that includes the attempt method, which is designed for this purpose.

Here's how you can modify the login controller to use the hashed password:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed
            return redirect()->intended('/dashboard');
        }

        // Authentication failed
        return redirect()->back()->withErrors(['email' => 'Invalid login credentials']);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, Laravel's Auth::attempt method will automatically check the provided email and password against the stored hashed password in the database. If the credentials match, the user will be authenticated, and you can redirect them to the intended page. Otherwise, an error message is displayed.

This assumes that your users table has a column named password where the hashed passwords are stored. Also, ensure that your login form includes an input field with the name password.

Make sure to adjust the routes and views according to your application structure. If you're using Laravel's default authentication scaffolding, you might already have a login view, and you can use the make:auth command to generate the necessary views and controllers.
Second Way
Authentication using custom redirection

use Illuminate\Http\Request;

class LoginController extends Controller
{
    // ... existing code ...

    protected $maxLoginAttempts = 3; // Amount of bad attempts user can make
    protected $lockoutTime = 300; // Time for which user is going to be blocked in seconds

    use AuthenticatesUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function redirectTo()
    {
        // Check the current URL and set the redirect path accordingly
        $currentUrl = request()->url();

        if ($currentUrl == 'your_specific_url') {
            return '/specific_path';
        } elseif ($currentUrl == 'another_url') {
            return '/another_path';
        }

        // Default redirect path
        return $this->redirectTo;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the default redirect path is set to /home, and the custom redirection logic is only applied if the current URL matches specific conditions. If none of the conditions are met, it falls back to the default redirect path ($this->redirectTo). Adjust the conditions and paths according to your specific requirements.

Third Way

public function login(Request $request)
    {
        log::info('inside login controller my');
        log::info('inside login controller mine'.$request);
        log::info($request);
        $phone = $request->mobiles_no;
        log::info($phone);
        $user = User::where('phone', $request->mobiles_no)->first();
        log::info($user);
        if(!$user){
            log::info('inside not $user ');
             $user = new User();
            $user->phone = $phone;
            $user->name = 'Tour operator';
            $user->save();
            $msg= '';
            return Eventmie::view('eventmie::auth.updates_profile',compact('phone','msg'));
        }
        else{
            if($user  && $phone){
                log::info('inside $user ');
                $user_email = User::where('email', '=', $user->email)->first();
                log::info($user_email);
                if($user_email->email==""){
                    log::info('inside $user if');
                    $msg= '';
                    return Eventmie::view('eventmie::auth.updates_profile',compact('phone','msg'));
               }
              else  if(!$user_email){
                    log::info('inside $user if');
                    return Eventmie::view('eventmie::auth.update_profile',compact('phone'));
               }
               else{
                log::info('inside $user else');
                \Auth::login($user);
                return $this->loginRedirect();
               }
            }
            else{
        $this->validate($request, [
            'email'    => 'required|email|max:512',
            'password' => 'required|max:512'
        ]);
        $flag = \Auth::attempt ([
            'email' => $request->get ( 'email' ),
            'password' => $request->get ( 'password' )
        ]);
        if ($flag)
        {
            // check if user is not disabled
            if(! \Auth::user()['status'])
            {
                \Auth::logout();
                return error_redirect( __('eventmie-pro::em.user_disabled'));
            }
            log::info('inside 2nd login controller');
            return $this->loginRedirect();
        }
        else
        {
            log::info('inside 3rd login controller');
            return error_redirect( __('eventmie-pro::em.notmatch'));
        }
    }
    }
    }
Enter fullscreen mode Exit fullscreen mode
  private function loginRedirect()
    {
        log::info('inside redirectnd login controller');
        // if coming from event checkout
        $redirect = '/';
        if(!empty(session('redirect_to_event')))
        {
            log::info('inside 2ndredirectnd login controller');
            $redirect = session('redirect_to_event');
            // forget session
            session()->forget(['redirect_to_event']);
        }
        log::info('inside 4thredirectnd login controller');
        // redirect to event
        $response = [
            'success' => true,
            'message' => 'Categoty retrieved successfully for edit.',
            'data' => $redirect
        ];
        Log::info("response to chala gya ");
        return redirect()->back();
    }
Enter fullscreen mode Exit fullscreen mode

Refrence

Summary

Authentication Using Auth attempt
redirect based on current url

Top comments (0)