Beertastic
Beertastic

Reputation: 711

Laravel 5.1 - I used Authentication, but now I need to access logged in user data on a custom controller?

I'm new to Laravel and have a problem I'm sure I'm being dumb over.

I've used the built in authentication to create a new user. Now I've created a dashboard area where I want to show user data (I'm building an internal messaging system so I want to get all messages assigned to the logged in user.. and to do that.. I need to get the current User ID.

I'm new as I said.. and I'm still fussy on how and where to use:

use path\to\files 

and how they relate to the framework.. I presume it's just like include or require in 'standard' PHP?

So, how can I get my user information?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        return view('dashboard', $user);
    }

}

I get this error:

'App\Http\Controllers\Auth' not found

So added this line, which just game the same error:

use App\Http\Controllers\Auth

Upvotes: 1

Views: 325

Answers (2)

user237329
user237329

Reputation: 819

When trying to use Auth::user(); you are accesing the Auth facade with is not in your App\Http\Controllers namespace. Try:

function index(){

        dd(\Auth::user());
}

Notice de \ before Auth.

Upvotes: 0

baao
baao

Reputation: 73231

You don't need Auth::user() in laravel 5. You can access your logged in user details by using $request->user()

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function index(Request $request) // Inject the Request class in your method
    {
        $user = $request->user()->id; // for example will give you the id of the logged in user
        return view('dashboard', $user);
    }

}

As a Sidenote in case you need it again:

For use statements you will need to provide the fully qualified class name. This means

namespace\Class 

I'm on mobile right now and don't know the name exactly, but you can have a look at your Auth Class to get the namespace.

Upvotes: 2

Related Questions