Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot access current user in controller #95

Closed
swilla opened this issue Sep 2, 2016 · 5 comments
Closed

Cannot access current user in controller #95

swilla opened this issue Sep 2, 2016 · 5 comments
Assignees

Comments

@swilla
Copy link

swilla commented Sep 2, 2016

I've tried the following:

auth()->user();
Auth::user();

All of them are returning null. I've tried to add some middleware to the route group:

Route::group([
    'prefix' => 'admin',
    'middleware' => [
        'auth',
        'role:admin,access_backend'
    ]
], function () {
    CRUD::resource('brands', 'Admin\BrandCrudController');
});

Am I missing something?

@axyr
Copy link

axyr commented Sep 2, 2016

laravel/framework#15072

And a shitload of other tickets regarding this issue...

@tabacitu
Copy link
Member

tabacitu commented Sep 10, 2016

Apparently this is a know breaking change in Laravel 5.3, just like @axyr said. I've found this solution:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class ProjectController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->projects = Auth::user()->projects;

            return $next($request);
        });
    }
}

from this article, but... it doesn't look very sexy to me.

NOTE YOU NO LONGER HAVE TO DO THIS - YOU SHOULD BE USING THE NEW SYNTAX

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class ProjectController extends Controller
{
    public function setup()
    {
         $this->projects = Auth::user()->projects;
    }
}

@tabacitu
Copy link
Member

We've included a simpler solution into Backpack\CRUD 3.1.20 - that middleware closure is run automatically inside a new CrudController::setup() method, so you can define your CRUD there and use session variables.

So: If you want to use Auth, you only need to rename your __construct() into setup(). Magic, I know :-)

Note: This change is backwards-compatible. You can still define everything inside __construct() if you want.

@tabacitu tabacitu self-assigned this Sep 26, 2016
@iwillhappy1314
Copy link

Awesome! test ok!

@Slaycaster
Copy link

Tried it, works like magic! Thanks!

This was referenced Apr 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants