How to get User()->id in Controllers (Laravel 8+) - laravel

I am trying to select tasks by user('id'), but I can't get it in a Controller, where I selecting data from DB.
I have tried many thing and some of them from stackoverflow, but it isn't working.
I tried:
1. $userId = Auth::check() ? Auth::id() : true;
2. Auth::user()->id;
3. public function getUserId(){
on Model} - and then get this value on Controllers
and some other things
I have the simplest code:
I installed registration: npm artisan ui --auth something like that
I installed vuejs (on Laravel)
I created api on Laravel, and some logic on vue
I didn't touch "app.blade.php" it's the same as it was.
I can get data, user: name, id and all what I want in file "app.blade.php" but I need those data in folder->file: App\Http\Controllers{{SomeController}}, but I don't know how.
Was someone in this situation?
How can I get user id in Controllers?
Thanks guys for earlier.

If you need user id, just use one of this :
auth()->id();
using Auth facade's
\Auth::id();
or, using Request instance
$request->user()->id
Follow this simple controller code, i showed 3 different way here :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class SomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function getUserId(Request $request)
{
$user = Auth::user(); // Retrieve the currently authenticated user...
$id = Auth::id(); // Retrieve the currently authenticated user's ID...
$user = $request->user(); // returns an instance of the authenticated user...
$id = $request->user()->id; // Retrieve the currently authenticated user's ID...
$user = auth()->user(); // Retrieve the currently authenticated user...
$id = auth()->id(); // Retrieve the currently authenticated user's ID...
}
}

Auth::user()->id;
This should work if you have Auth middleware on that controller method where you try to get it, please check do you added that middleware.
For checking you can use php arisan route:list command.

Is someone still searching an answer on this question. I have some explanation how can you do this.
Laravel has a Router which routes authorization process through that Controller which you want, so you should redirect that process on your Router and in Controller create constructor which allows you to take user id.
How can you do that?:
1. First of all you should find Controller and Route which responsible for authorization and registration users.
In my case it was:
a)App\Http\Controllers\HomeController
b)routes\web.php
2. Second, you should redirect your authorization Router to the Controller where you trying to get Auth::id();
In my case it was:
App\Http\Controllers\TasksController
so, in routes\web.php I did this:
//was
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
//was
Auth::routes();
//was
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
//added
Auth::routes();
//added
Route::get('/home', [App\Http\Controllers\TasksController::class, 'index'])->name('home');
perhaps you should have index function on that controller
3. Third you should add constructor in your controller where you want to get user id, this constructor I took from HomeController, it already was there.
In my case it was:
public function __construct()
{
$this->middleware('auth');
}
code with function on my TasksController:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$userId = Auth::check() ? Auth::id() : true;
}
And now I can take user id.
PS: constructor I added on the top in class TasksController in Controller

Related

id parameter of Auth return an error -Laravel API

This is an API to upload files. In this, admin as well as other users can upload files. so, i need to find the person who is uploading it and want to store it to the column uploadedBy. when tried with the below code , i get the error Trying to get property 'id' of non-object . I'm not ssure whether i can get the id like this. Pls help me with ur suggestions.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Files;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function upload(Request $req)
{
$file=$req->file('file_name');
$dataToInsert = array();
$filePath= uniqid().'-'.now()->timestamp;
$dataToInsert['FilePath'] = $filePath;
$dataToInsert['uploadedBy'] = Auth::user()->id;
$dataToInsert['Userid'] = $req->bearerToken();
Files::create($dataToInsert);
}
}
EDIT: Added the middleware . Now the error is that API simply shows the msg unauthenticated.
You should put your route on auth middleware, this route can be accessed after authenticated only, so that you can get user info by auth()->user().
To access id only, just auth()->id(), this can return null if the application is not authenticated.
Please note that you pass gate name in auth() helper, eg: auth('api')->id().
You can get the id of the authenticated user by auth()->id()
Edit: You need to be logged in first, or it will throw an error

Laravel override Login controller, login(). How do i retrieve logged in user data if i overwrite the login controller. I tried to get auth() data

I used laravel like 4 years ago. Had to work on a project on laravel and tried using my own authentication methods but mybad forgot there was already inbuilt better security authentication. I understand if my question seem to be basic.
As you can see the commented line "$userID = Auth::user()->userID;" the auth() is null therefore, userID cannot get its id from null. I am unable to get user session data in any other controllers as well.
Any kind of help or suggestions is appreciated.
P.S. i have used the default login and registration inbuilt function only required function like login is override code. I am using laravel v 4.2.3. I tried passing the userid as url parameter but then discarded it as inbuilt session data makes it more secure and easier
the login function of my controller looks like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function login(Request $request){
$user = new User(); //my model User
$result=$user->login($request); //result has the id of the user
if ($result) {
//$userID = Auth::user()->userID;
return redirect()->route('homepage');
}else{
return redirect()->route('login');
}
}
}
model for user login()
//Auth user then let them login
public function login($request){
$email = $request->input('email');
$password = $request->input('password');
$result=DB::table('users')
->where('email', $email)
->where('password', $password)
->get();
return $result;
}
My Routes.. its default route of "Auth::routes();"
Route::get('/homepage/{userID?}', function($userID = null){
return view('index', ['userID' => $userID]);
})->name('homepage');
Route::get('/evaluate/{userID?}', function ($userID = null) {
return view('evaluate', ['userID' => $userID]);
})->name('evaluate');
I installed a fresh new laravel and tried my code again and somehow it worked. Must have made some errors when trying to override the codes. Thank you

Custom route for edit method without ID in URL

I want to make a settings screen for my users, and I want the URL to be easy an memorable: domain.com/user/settings
I want this route to point use the UserController#edit method, however, the edit() method requires ID parameter.
Is there someway I can use user/settings URL without specifying the ID in the URL, but still use the same edit() method in the UserController?
The edit URL could be use without any parameter. In that case you can mention the user in controller.
Route
Route::get('user/settings');
Controller
public function edit()
{
$user = Auth::user();
}
Seems like I managed to solve it?
web.php:
Route::get('user/settings', 'UserController#edit')->name('user.settings');
Route::resource('user', 'UserController');
UserController.php:
public function edit(User $user = null)
{
$user = Auth::user();
}

Laravel using user id in route

So I have a route profile/{user_id}
How do I redirect user to that URL when they click on link?
Here's my controller:
{
function checkid($user_id) {
if (Auth::check())
{
$user_id = Auth::id();
return view('profile', [
'id' => $user_id
]);
}
}
}
Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!
<?php
namespace App\Http\Controllers;
class RandomController extends Controller {
public function index()
{
return view('profile');//use auth facade in blade.
}
}
In your routes use a middleware to prevent none authenticated users from reaching this method
<?php
Route::group('/loggedin', [
'middleware' => 'auth',
], function() {
Route::get('/profile', 'RandomController#index')->name('profile.index');
});
Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!
<h1>Hi! {{Auth::user()->name}}</h1>
View profile
Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.
if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).
Let me know if you need help with anything else.
You can redirect with the redirect() helper method like this:
return redirect()->url('/profile/' . $user_id);
But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.

Laravel 5.4 Sessions and Auth::user() not available in controller's constructor

I would like to use a User class throught the application. So, I would like to create CustomUser and then inject it into controllers that need it (it would be most of them).
Now, I create an empty instance in serviceprovider. Next, I want to fill it with data that are already saved in Auth::user(). After long time I have not found where to do it.
Auth::user() is empty in middlewares, but is filled with the user data in controllers. I am missing the step where Laravel queries the database and fills Auth:user() with data. I want to avoid making the same query again.
Thanks for any help!
You can use base controller with __get() method. For example:
class Controller
{
public function __get(string $name)
{
if($name === 'user'){
return Auth::user();
}
return null;
}
}
And in the child controllers can call $this->user
Since Laravel 5.3, you do not have access to sessions in controller constructors. This is because the middleware has not been run yet. I know it's difficult to locate, but in the migration documentation from 5.2 > 5.3 (you're probably on 5.4), it shows that the proper way to resolve data from sessions (which auth() is just a wrapper around a session() call to get the user), is to use the following method:
class MyController extends Controller {
protected $user;
public function __construct() {
$this->middleware(function ($request, $next) {
$this->user= auth()->user();
return $next($request);
});
}
}
Then $this->user will reference the auth user to any methods inside of this controller.
Hopefully his helps.
In Laravel 5.6 i used this
$this->middleware(function ($request, $next) {
$id = Auth::user()->id;
$res = $this->validateAnyFunction($id);
if(!$res){
//to redirect to any other route
return $next(redirect()->route("any")->with("failed","Invalid")->send());
}
//this is used to proccess futher funcitons of controller
return $next($request);
});

Resources