Raggaer
Raggaer

Reputation: 3318

Laravel controller construct

I started with laravel few days ago and I'm facing this issue:

The NO is never returned!

This is Controller, do you have any idea why?

  Class TestController extends BaseController {

    public function __construct()
    {
        if (!Auth::check()) return 'NO';
    }

    public function test($id)
    {   
        return $id;
    }
}

Upvotes: 20

Views: 83558

Answers (2)

manuelpgs
manuelpgs

Reputation: 1372

For laravel 5.x:

public function __construct()
{
    $this->middleware(function(){
        if (!Auth::check()) return 'NO';
    });        
}

Upvotes: 1

Andreyco
Andreyco

Reputation: 22862

<?php

class BaseController extends Controller {

    public function __construct()
    {
        // Closure as callback
        $this->beforeFilter(function(){
            if(!Auth::check()) {
                return 'no';
            }
        });

        // or register filter name
        // $this->beforeFilter('auth');
        //
        // and place this to app/filters.php
        // Route::filter('auth', function()
        // {
        //  if(!Auth::check()) {
        //      return 'no';
        //  }
        // });
    }

    public function index()
    {
        return "I'm at index";
    }
}

Upvotes: 28

Related Questions