I want to return the users info to my view when a user logs in but I keep getting an error message that says "Undefined variable: user"
Here is my controller code:
public function postLogin()
{
$credentials = array(
'email' => \Input::get('email'),
'password' => \Input::get('password')
);
try
{
$user = \Sentry::authenticate($credentials, false);
if ($user);
{
$user = \Sentry::getUser();
\Notification::succes('Succesvol ingelogd als,'. $user->name);
return \Redirect::back()-with($user);
}
}
catch(\Exception $e)
{
\Notification::error($e->getMessage());
return \Redirect::back();
}
}
and in my view I try to use the $user variable but then I get the error.
When you do:
Redirect::back()->with('user',$user);
In your new request you must get the user from the Session:
$user = Session::get('user');
and pass it to your view:
return View::make('view')->with('user', $user);
Because Laravel doesn't create global variables as it does when you:
return View::make('view')->with('variableName', $value);
Related
i have this function for get orders for only authenticated user:
function show($uid) {
try {
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}
it is a end point for API in this route:
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/order/{id}', [OrdersController::class, 'show']);
});
but now if anyone just add any uid, he can display all orders...
my question is how can i protect this function so just auth user can fetch data: and i have used Sanctum in my project
in laravel with blade i just do like this:
function show() {
$uid = auth()->id();
try {
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}
Thank you all...... I have found the solution, i could find the id of Authenticated user simply by this since i use the guard (sanctum):
auth('sanctum')->user()->id
this will give me the id for auth user depending on the token.
and the solution will be like this:
function show(Request $request) {
try {
$uid = auth('sanctum')->user()->id;
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}
I have a function in controller checklogin() which checks the user details. I want to store into session. So I can get the name of the user and display in blade view
Controller
public function checklogin(Request $request)
{
$req=$request->validate([
'name'=>'required',
'email'=>'required|email',
'password'=>'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#_!]){8,}/'
]);
$userdata = array(
'name' => $request->input('name') ,
'email'=>$request->input('email'),
'password' => $request->input('password')
);
if (Auth::attempt($userdata))
{
$data = $request->session()->put('user',$userdata['name']);
dd($data) ; //returning null
return redirect('/home');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
No need to store logged in user detail in session.You can call auth helper function which will return auth instance.
{{auth()->user()->name}}
if you have both logged in or guest page same then you can do null check
{{ auth()->user()!=null?auth()->user()->name:null }}
I am new to Laravel so I only have a vague idea of what I am doing. I am doing a feature tests and a function that I know fires when I use postman to test the api, but doesn't during the test. Here is the test
public function testVerify(){
$this->createTestUserParams();
$response = $this->post(route('register'), $this->user_params);
$response->assertOk();
$user = User::where('email','test#gmail.com')->first();
if($user){
$token = $user->verifyUser->token;
$id = $user->verifyUser->user_id;
$response2 = $this->post(route('email.customVerify'), ['user_id' => $id, 'token' => $token]);
$response2->assertOk();
//$user->markEmailAsVerified();
$this->assertNotNull($user->email_verified_at);
}else{
$this->fail('should find a user');
}
}
and here is the code for the function the route controller points to
public function customVerify(Request $request){
if(!isset($request->user_id)){
return response()->json(['message' => 'No user ID'],400);
}
if(!isset($request->token)){
return response()->json(['message' => 'No user token'],400);
}
$user = User::where('id',$request->user_id)->first();
if($user == null){
return response()->json(['message' => 'Bad User Id'],400);
}
if ($user->hasVerifiedEmail()) {
return response()->json(['message' => 'Already verified'],400);
}
if($request->token == $user->verifyUser->token){
if($user->markEmailAsVerified()){
event(new Verified($user));
VerifyUser::where('user_id',$user->verifyUser->user_id)->first()->delete();
return response()->json(['message' => 'Everything is swell'],200);
}
}else{
return response()->json(['message' => 'Bad token'],400);
}
}
My problem is that the field email_verified_at is coming back null when it shouldn't.
The strange thing there is an $response->assertOk(); and response will only be OK if the markEmailAsVerified() function fires successfully, otherwise the response will not be code 200. And the markEmailAsVerified() function is doing what it is supposed to because when I invoke it byitself in the test where it is commented out, the test comes back fine.
I am using the passport library for auth if that helps.
Trying getting a fresh instance of your user?
$user = $user->fresh();
$this->assertNotNull($user->email_verified_at);
I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user
I have a Google+ login on my app with Laravel Socialite. When the login is done I have a callback to connect the user (I create her in database if necessary).
But I want to restrain the connection to only the company (email like "example#company.com", so only the email with "company.com").
Can I do it with Laravel Socialite ? I can make the verification manually in my callback but if Socialite can do it, it's better.
Thank you
My callback :
public function handleProviderCallback($provider){
$user = Socialite::driver($provider)->user();
if ($user) {
$local_user = User::whereEmail($user->getEmail())->first();
// If we don't have a user create a new user
if (!$local_user) {
$fragment = explode(' ', $user->getName());
$local_user = User::create([
'first_name' => isset($fragment[0]) ? $fragment[0] : '',
'last_name' => isset($fragment[1]) ? $fragment[1] : '',
'email' => $user->getEmail(),
'last_seen' => Carbon::now(),
'password' => ''
]);
$local_user->roles()->attach(Role::whereName('User')->first());
}
auth()->login($local_user);
}
return redirect($this->redirectTo);
}
You have a step by step guide for domain restriction.
In controller you need to specifiy these actions:
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with #company.com to login
if(explode("#", $user->email)[1] !== 'company.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
No, you can’t do it in Socialite itself because Socialite is just a mechanism of retrieving tokens from OAuth-compliant servers.
If you only want to accept users with a particular email suffix, then that’s business logic so something you should handle in your callback:
public function handleProviderCallback()
{
$user = Socialite::driver('google')->user();
if (Str::endsWith($user->getEmail(), '#example.com')) {
// Look up user and authenticate them
}
abort(400, 'User does not belong to organization');
}