Condition To Run __Construct Function

Asked

Viewed 122 times

1

I created a function __construct in the Controller.php of Laravel 5.

And this function is obviously running even on the Login screen, on Auth.

Is there any way I can put as a condition, run the function inside the __construct only when the user is logged in ?

I know a way to do, at the beginning of the function I put:

if(Auth::check())
    # Roda Função

But there is another way ? That way up every time it will do the check.

__construct

public function __construct(){
    if(Auth::check()){
        # Monta Menu e Sub Menu
        $menu       = Menu::orderBy('posicao')->get();

        $arrMenu    = array();

        foreach($menu as $itemMenu){
            $arrMenu[$itemMenu->titulo]['titulo']   = $itemMenu->titulo;
            $arrMenu[$itemMenu->titulo]['link']     = $itemMenu->link;
            $arrMenu[$itemMenu->titulo]['icon']     = $itemMenu->icon;
            $arrMenu[$itemMenu->titulo]['slug']     = $itemMenu->slug;

            $submenu            = Submenu::whereIdMenu($itemMenu->id)->orderBy('posicao')->get();

            foreach($submenu as $itemSubMenu){
                $arrMenu[$itemMenu->titulo]['submenu'][$itemSubMenu->titulo]['titulo']  = $itemSubMenu->titulo;
                $arrMenu[$itemMenu->titulo]['submenu'][$itemSubMenu->titulo]['link']    = $itemSubMenu->link;
            }
        }

        # Total de Chamados Agrupado por Status no Menu
        if(Auth::user()->id_role == 1){
            $chamados = DB::table('chamados')
                        ->rightJoin('status', 'status.id', '=', 'chamados.id_status')
                        ->select(DB::raw('count(chamados.id) as total, status, status.id as id_status'))
                        ->orderBy('status.id')
                        ->groupBy('status')
                        ->get();
        }
        else{
            $chamados = DB::table('chamados')
                        ->select(DB::raw('count(chamados.id) as total, status, status.id as id_status'))
                        ->orderBy('status.id')
                        ->groupBy('status')
                        ->rightJoin('status', function($join){
                            $join->on('status.id', '=', 'chamados.id_status')
                                 ->where('id_departamento', '=', Auth::user()->id_departamento)
                                 ->where('id_user', '=', Auth::id())
                                 ->orWhere('id_user', '=', NULL);
                        })
                        ->get();
        }

        $totalFinal = 0;

        foreach ($chamados as $key => $value){
            $totalChamado[$value->id_status] = $value->total;
            $totalFinal                     += $value->total;
        }

        # Coloca em Array o Menu e o Total de Chamados para Colocar no Share
        $arrShare = array(
            'menu'      => $arrMenu,
            'chamados'  => $totalChamado,
            'total'     => $totalFinal
        );

        view()->share('arrShare', $arrShare);
    }
}

1 answer

1


There’s no other way, as far as I know. If you want to verify that a user is logged in or not, you will always have to check every request made by the user.

In that case, I wouldn’t use the method __construct, but yes the middleware.

namespace App\Http\Middleware;

use Closure;

class IsAuthMiddleware
{

    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            // Faço a minha mágica aqui
        }

        return $next($request);
    }

}

To set this up, you have to change the AppKernel:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
]

In the file of routes.php:

Route::get('admin/profile', ['middleware' => 'auth', function () {
    //
}]);
  • I use Middleware to this end. The real problem is that __construct made a function that creates a MENU. And how the MENU goes on all pages created in Controller.php. I’ll post.

  • No, no, @Taopaipai. In that case don’t do so! Controller is for requests. View is another layer. Use the View::share to generate this menu. So you will share a variable (or more) for all views.

  • Use the BeforeMiddleWare for that reason

  • You’re a little confused yet... I’ll create a BeforeMiddleware. I put the function that creates the MENU inside this ? Then log in AppKernel and then I put it on Route ?

  • It is that you edited the question later. In fact, you will only use the BeforeMiddleWare. There you will register the variable in View::share.

  • But what is the sequence of how to do it ? It’s like I said in the comment above ?

  • @Taopaipai, I don’t understand the "sequence" question. You make the statements. It is Laravel who will put first the middleware running, then redenrization.

  • I’ll tell you what I did sequentially: php artisan make:middleware BeforeMiddleware. Then I took the function that was on Controller.php and put inside the handle of the archive Beforemiddleware.php. I registered on Kernel. I have to put on the route now ?

  • I got it, bro. You don’t know shit. Thanks!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.