Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  1. I installed registration: npm artisan ui --auth something like that
  2. I installed vuejs (on Laravel)
  3. 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.

like image 934
K.Igor Avatar asked Nov 11 '20 13:11

K.Igor


1 Answers

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...
    }
}
like image 84
muhive Avatar answered Sep 28 '22 06:09

muhive