Hi im storing data in database but when i use Auth::user()->name it is not working. in my other controller its working. But when i hard coded the name and the id it works. I already imported auth and still get the same issue. Thanks for the help. this is weird .
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ForumPost;
use Auth;
public function create_discussion(Request $request){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = Auth::user()->name;
$create->comment_frequency = 100;
$create->user_id = Auth::user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}
btw im using vue as a front-end.
You need to import/add
use Auth;
use App\User;
Than save logged in user as this in your controller:
public function create_discussion(Request $request, $id){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = auth()->user()->name;
$create->comment_frequency = 100;
$create->->user_id = auth()->user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}
This is from Laravel 7.14. You are not passing the id in your function.
You can Use in your controller
get User to your controller.. user auth in your controller head.
use Auth;
use App\User;
Get User id from :
Auth::id();
Get User Name from
Auth::user()->name;
If you are not authenticed user, then Auth::user()->id won't work.
Do a Auth::check() before, to be sure that you are well logged in :
public function create_discussion(Request $request){
if(Auth::check()){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = Auth::user()->name;
$create->comment_frequency = 100;
$create->user_id = Auth::user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
} else {
return response()->json([
'message' => 'You are not authentic user. '
]);
}
}
Before creating a forum you can do an auth()->check()
if(auth()->check()){ //returns true or false
$user = auth()->user();
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = $user->name;
$create->comment_frequency = 100;
$create->user_id = $user->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}else{
return response()->json(['message'=>'not authenticated could not create a forum.']);
}
may be this will work.
be sure that you are logged in.
and use that
auth()->user()->name;
auth()->id();
it's the same.
if error 500 , check the .env is exists then try
php artisan key:generate
php artisan cache:clear
php artisan config:clear
I manage to get it working by creating a props and pass it to my post request. I dont know why that auth()->user()->.... is not working.I think this will be a problem when the proj. is getting larger. Thanks for the answers
Related
I developed a laravel API for flutter app. Here's my AuthController and the following are the function. What I want to do is that once I submit the request on postman, it will display the current info of the logged-in user. Currently, I manage to retrieved the info but it instead display the data of the first user in the table instead of the corresponding user that I logged in(in postman). How do I fix this ? Please help
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
//Check email
$user = User::where('email', $fields['email'])->first();
//Check password
if (!$user || !Hash::check($fields['password'], $user->password)) {
$result = [];
$result['status'] = false;
$result['message'] = "Bad creds";
return response()->json($result);
} else {
$result = [];
$result['status'] = true;
$result['message'] = "Login successfully";
$data = User::first(['staff_id', 'name']);
$result['data'] = $data;
return response()->json($result);
}
}
}
In your else block the
$data = User::first(['staff_id','name']);
means that it will fetch the first user in your database. Instead of querying again you can use the already declared $user since it is the data that you are looking for.
$data = $user;
How about :
$data = [
'staff_id' => $user->staff_id,
'name' => $user->name,
];
Logic
I have store function and it's returning data of users in the group.
The person who saves this data is also included of group users.
Now I want to exclude s/he from group users when data returns.
code
I've commented the code so you can understand it better.
public function store(Request $request)
{
$user = $request->user(); // current user who should be excluded
$group = Group::where('id', $request->input('group_id'))->first();
$message = new GroupMessage;
$message->group_id = $request->input('group_id');
$message->user_id = $user->id;
$message->note = $request->input('newMessage');
$message->message_id = $request->input('message_id');
$message->save();
// returning data
// 'user' is current user (also available in 'group.users')
// remove current 'user' from ('group.users')
$ms = GroupMessage::where('id', $message->id)->with(['user', 'group', 'group.users'])->first();
return response()->json([
'data' => new NotesResource($ms),
'message' => 'Message sent successfully.'
], 200);
Log::info('message data sent.');
broadcast(new MessageSent($message))->toOthers();
}
Screenshot
here is how code above returns data
Any idea?
You can exclude this User using Eager Loading Constraints:
$ms = GroupMessage::where('id', $message->id)
->with(['user', 'group.users' => function ($query) use ($user) {
$query->where('users.id', '<>', $user->id);
}])->first();
Laravel 7.x Docs - Eloquent - Relationships - Constraining Eager Loads
I'm trying to login a user through laravel socialite. Everything is working fine but the user is not getting logged in!
I'm getting response from facebook, saving the response in the database and trying to login after that.
here is the code:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;
use DB;
use Log;
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
$findUser = User::where('email', $social->email)->first();
if ($findUser) {
// dd($findUser); **************** This returns information of the user who is trying to login through facebook
// dd(Auth::login($findUser, true)); ***************** This line returns null
if (Auth::login($findUser, true)) {
// dd(Auth::loginUsingId($findUser->id, true));
redirect()->route('dashboard');
} else {
return 'Error'; //**************** This get echoed on the screen
}
} else {
$user = new User();
$user->name = $social->name;
$user->email = $social->email;
$user->avatar = $social->avatar;
$user->provider = $provider;
$user->id = $social->id;
$user->password = bcrypt('password');
$user->save();
}
if (Auth::login($user)) {
return redirect()->intended('/home');
} else {
return 'Error';
}
}
Neither register, nor login is working.
The login() method doesn't return anything so if (Auth::login($findUser, true)) will never pass.
Also, it might be worth using the firstOrCreate() to make your method smaller:
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
User::unguard();
$user = User::firstOrCreate([
'email' => $social->email,
], [
'id' => $social->id,
'name' => $social->name,
'avatar' => $social->avatar,
'provider' => $provider,
'password' => bcrypt('password'),
]);
auth()->login($user, true);
return redirect()->intended('/home');
}
If you want to check if the User is signed in then you can use the auth()->id() method to retrieve the current authenticated user's id and then compare that to the $user->id:
if (auth()->id() !== $user->id) {
return 'Error';
}
Obviously, if you prefer to use the Auth facade instead of the auth() helper function then you can use Auth::id() instead of auth()->id()
I am having issues passing user details after authenticating the user. The variable $newUser has the required information, but it can't be passed to the user.index view. I am using Laravel 5.1.
Route::get('user/home', ['as' => 'home', function () {
return view('user.index');
}]);
Route::get('{provider}/login', function ($provider) {
global $newUser;
OAuth::login($provider, function ($user, $userdetails) {
$newUser = $userdetails;
$email = DB::table('users')->where('email', $newUser->email)->value('email');
if( isset($email)) {
echo "Welcome " . $newUser->full_name . " <br/>";
}
else {
echo "New User! <br/>";
$user->name = $newUser->full_name;
$user->email = $newUser->email;
$user->save();
}
});
$newUser = (array) $newUser;
return view('user.index', $newUser);
});
Try:
view('user.index', compact('newUser'));
Well just wondering, why don't you use a controller and make your code more explicit so that coming back to your coding 6 months from now would be easy for you to understand.
Anyway, if your using the Auth facade, you should be able to use
Auth::user()
inside your view to retrieve it or try seeing the available method of the OAuth class. Or if you want to keep your code as it is try
return view('user.index', compact('newUser'));
i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"
Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.
You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;
Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}
As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.