galih56
380
11
Laravel

Auth::user() returns null value

Posted 4 months ago by galih56

0

I'm working on username authentication. I thought my LoginController is working perfectly.But when i go to the page and do login.The page will be stay on login page.I checked my code,when i use dd(Auth::user()) in my HomeController. it always return null value.

i read some discussion on stackoverflow.People said i have to use this in the loginController's constructor.

$this->middleare(function($request,$next){
    $this->user=Auth::user();
    return $next($request)
})

but it doesn't work in my project.

I'm sure the only reason why my login page cannot redirect to the next page is because the Auth::user() have null value.But i don't know how to fix that.

can someone help me??

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Auth\Validator;

class LoginController extends Controller
{


    use AuthenticatesUsers;


    protected $redirectTo = '/index';

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

    protected function authenticated(Request $request)
    {
        if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {

            return redirect('/');
        }
    }
    public function username()
    {
        return 'username';
    }
    protected function validateLogin(Request $request)
    {
        /*$this->validate($request, [
            "user_name" => 'required', 'user_password' => 'required',
        ]);*/
        $messages = [
            'username.required' => 'Username harus diisi',
            'username.unique' => 'Username sudah ada',
            'password.required' => 'Tolong isi password terlebih dahulu',
            'password.min' => 'Password harus diisi minimal 6 karakter.'
        ];
        return $this->validate($request, [
            'username' => ['required', 'string', 'max:150'],
            'password' => ['required', 'string', 'min:6'],
        ], $messages);
    }
}

HomeController.php

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{

    public function __construct()
    {
        dd(Auth::user()); //this return false
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}

Please sign in or create an account to participate in this conversation.