Etali
Etali

Reputation: 151

Authentication in Laravel using 2 tables

I want to create a connection system using 2 tables with Laravel in fact my tables are like this

Users

Id Username Id_agence

Agences

Id Code password

I use the foreign Key id_agence in users table

Upvotes: 0

Views: 279

Answers (3)

Etali
Etali

Reputation: 151

public function traitement()
    {
        request()->validate([
            'username' =>  ['required'],
            'pass' => ['required']
        ]);



        $result = auth()->attempt([
            'username' => request('username'),
            'password' => request('pass'),
        ]);

        if($result){  
            flash("Your now connected")->success();

            return redirect('/home');
        }

        return back()->withInput()->withErrors([
            'pass' => 'Incorrect identifier'
        ]);
    }

here is what I have try first

Upvotes: 0

Jordan
Jordan

Reputation: 1

if(User::where('username', $request->username)->exists())
{
     $user = DB::table('users')
                       ->leftJoin('agences', 'users.id_agence', '=', 'agences.id')
                      ->where('users.username', $request->username)
                      ->first();

     $auth = Hash::check($request->password, $user->password);

         if($user && $auth)
         {
              Auth::login($user);

              Session::flash('success', 'LogIn Successful!');
              return redirect()->intended(route('user.index'));
         } 
     else
         { 
             //If unsuccessful then redirect back
             Session::flash('error', 'Email or password is incorrect!');

             return redirect()->back()->withInput($request->only('email', 
             'remember'));
         } 
 }
  1. Check if the username requested via the form or any other method exists in the users database or not.
  2. If true join the "agences" table with the user table to fetch all the information along with the stored hashed password.
  3. Use the Hash::check method which allows to verify a given plain text corresponding to given hash.
  4. Check if both conditions are true then you authenticate a user via Auth::login and redirect it to intended route else redirect back.

Upvotes: 0

Hafijur Rahman Bokther
Hafijur Rahman Bokther

Reputation: 539

$user=DB::table("Users")
                        ->join("Agences",'Users.Id_agence','Agences.id')
                        ->where("Users.Username","The username")
                        ->select("Agences.password as password")
                        ->first();
if(Hash::check("Your plain password",$user->password)){
----
}

Upvotes: 3

Related Questions