Reputation: 9066
Here inside store method data of newly registered user are saved in database and then new user is logged in.
After user authentication inside store method the controller will trigger the show method and inside the show method dd(Auth::user()) returns null null. I have my routes and controllers in Route middleware group. It means I have no logged in user.
How I can solve this?
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);
}
}
my user model:
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;
}
Upvotes: 2
Views: 3200
Reputation: 1952
Before the last if
of your store function and after saving the $user add 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']]);
}
Now the Auth::user()
will always return $user
Upvotes: 1