Home > database >  ErrorException Undefined variable: username LARAVEL
ErrorException Undefined variable: username LARAVEL

Time:07-31

Just to preface this, I have gone through most of the answers that are aligned to my question, pretty much I have an undefined variable for the user.

I want to log in the user with the session and display the user's name after logging in on the dashboard .following is my code.

<?php

namespace App\Http\Controllers;

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

class MainController extends Controller
{
    function login1(Request $request){
      $username = $request->input('username');
      $password = $request->input('password');


      $data = DB::table('users')->where(['username'=>$username, 'password'=>$password])->get();
      if(count($data)>0){
       $request->session()->put('username',$data);
        return redirect('dashboard');
      }
else{
    
        echo "error";
    
        $notification = array(
                'message' => 'User Does not Exists!',
                'alert-type' => 'error'
            );
            return back()->with($notification);
      
      
      
}
}}




CodePudding user response:

To show a page and pass variables to it, this is one way to do it:

$data = [1,2,3,4];
$username = 'my_name';

return view('dashboard', compact('data', 'username'));

CodePudding user response:

Try this, Assuming your user model has been set correctly ;

    function login1(Request $request){

      $user = User::where('username',$request->username)->where('password', $request->password);
      
if ($user->exists()) {
            $user = User::where('username', $request->username)->where('password', $request->password)->first();
            Auth::login($user, true); 
            return redirect('dashboard');   
} else {
 return Redirect::back()->withErrors(['msg' => 'Incorrect username or password']);
}

}
  • Related