首页 文章

即使用户已登录,Auth :: user()也会返回Null

提问于
浏览
1

这里新注册用户的内部存储方法数据保存在数据库中,然后新用户登录 .

在store方法内进行用户身份验证后,控制器将触发show方法,并在show方法内部dd(Auth :: user())返回null null . 我在Route中间件组中有路由和控制器 . 这意味着我没有登录用户 .

我怎么能解决这个问题?

public function store(Request $request)
{
    //
    $data = $request->all();
    print_r($data);
    $rules = array(
       'username'  => 'unique:users,username|required|alpha_num',
       'password'  => 'required|alpha_num',
       'full_name' => 'required',
       'email'     => 'required|unique:users,email'
    );

    // Create a new validator instance.
    $validator = Validator::make($data, $rules);
    if ($validator->fails()) {

        $errors = $validator->messages();
        return Redirect::route('user.create')->withErrors($validator);

    } else {

        $user = new User();
        $user->username = $request->username;
        $user->password = Hash::make($request->password);
        $user->full_name = $request->full_name;
        $user->email = $request->email;
        $user->joined = date('d-m-y H-i-s');
        $user->save();


        if(Auth::attempt(['username' => $request['username'],'password' => $request['password']])){
            return redirect()->route('user.show',[$request['username']]);
        }
    }
}

public function show($user)
{

    $indicator = is_numeric($user)?'user_id':'username';
    $info=User::where($indicator,'=',$user)->get()->first();
    if($info){

       dd(Auth::user());  // returns null
       $data = array('info' => $info);
       return View::make('user.show')->with('info',$data);
    }else{
         echo "this user doesn't exist";

         $info = User::where($indicator,'=', Auth::user()->$indicator)->first();
         $data = array('info' => $info);
         return View::make('user.show')->with('info',$data);
    }
}

我的用户模型:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{

    use \Illuminate\Auth\Authenticatable;
    protected $table = 'users';
    public $timestamps = false;

}

1 回答

  • 1

    在商店功能的最后 if 之前和保存$ user之后添加 Auth::login($user);

    $user->save();
    
         Auth::login($user);
    
    //In case of adding a new user, Even the below If is not necessary 
         if(Auth::attempt(['username'=>$request['username'],'password'=>$request['password'    ]])){
    
    
            return redirect()->route('user.show',[$request['username']]);
        }
    

    现在 Auth::user() 将始终返回 $user

相关问题