Use Auth class in configuration file in Laravel

2

I'm using barryvdh / laravel-elfinder . This generates the configuration file /config/elfinder.php. Within this file, I inform the way to upload ElFinder files.

I need every user to have their upload folder. I thought of creating a $dir variable according to the id of the logged-in user but I can not use the Auth class inside the /config/elfinder.php file.

Are you able to get the user logged in any other way?

The file looks like this:

<?php

$dir = 'arquivos';    
return array('dir' => [$dir] );

I want something like this:

<php

$dir = 'arquivos/'.Auth::id();
return array('dir' => [$dir] );

I've tried this:

<?php

use Auth;
$id=Auth::id();

$dir = 'arquivos/'.$id;    
return array('dir' => [$dir] );

And returns this error:

Warning: The use statement with non-compound name 'Auth' has no effect in /var/www/html/dna/config/elfinder.php on line 3

Fatal error: Class 'Auth' not found in /var/www/html/dna/config/elfinder.php on line 5
    
asked by anonymous 31.10.2016 / 17:56

1 answer

3

This error usually happens because the configuration file is loaded before the internal processing that Laravel does for the Auth class (which is an alias).

In addition to this problem, depending on where in the application you might want to try to access the value of Auth::user , the return can be null regardless of whether it is logged in or not. This is because data from Auth is only accessible after loading these middlewares below:

    \Tmt\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,

They are responsible for the session, cookies and the like.

Solution

You can consider using the config function to be able to define according to the user logged in within a Middleware. Because using a middleware, it is working with data coming from the session, since they have already been loaded by previous middlewares.

For example

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // Restante do código

        config(['elfinder.dir' => ['arquivos/' . auth()->user()->id]])

        return $next($request);
    }
}

It's nice to note that the idea of using config is to work with immutable data.

It might still be interesting to see if the library you are using does not have a method for you to define which directory to work on.

    
31.10.2016 / 18:42