Search code examples
phplaravelelfinder

where can I change configurations on the fly after User autenticaton in laravel?


I am using elfinder laravel package to manage and organize files.

It has a elfinder.dir config options that used to specifies a directory that user can upload files to it.

Now I want to change (or create) this option to a directory same name as logged in User username.

For that I wrote some codes in a middleware that runs after user authentication for limit access of user to admin panels. like this :

class IsAdmin
    {

        public function handle ($request, Closure $next)
        {
            if (Auth::check()) {

                $username = Auth::user()->username;

                if (!File::exists(public_path('upload') . '/' . $username)) {
                    File::makeDirectory(public_path('upload') . '/' . $username, 0775);
                }
                Config::set('elfinder.dir', ["upload/$username"]);

                return $next($request);
            }
            return Redirect::to('/admin/login');
        }
    }

As you can see if there no directory same as username it will be create.

But I want to know it is right that I do this operations in a middleware or there are another(or proper) place to that ?


Solution

  • According to @yannis-berrouag answer and authentication events in l5.3 docs I do this.

    First I added this to EventServiceProvider.php :

    'Illuminate\Auth\Events\Authenticated' => [
            'App\Listeners\SetElfinderConfigs',
    ],
    

    Then I added my desired actions to SetElfinderConfigs listener like this :

    class SetElfinderConfigs
        {
            /**
             * Create the event listener.
             *
             * @return void
             */
            public function __construct ()
            {
                //
            }
    
            /**
             * Handle the event.
             *
             * @param  Authenticated $event
             *
             * @return void
             */
            public function handle (Authenticated $event)
            {
                $username = $event->user->username;
                if (!File::exists(public_path('upload') . '/' . $username)) {
                    File::makeDirectory(public_path('upload') . '/' . $username, 0775);
                }
                Config::set('elfinder.dir', ["upload/$username"]);
            }
        }