拉拉维尔控制器结构

2022-08-30 21:07:00

几天前,我从laravel开始,我面临着这个问题:

永远不会回来!NO

这是,你知道为什么吗?Controller

  Class TestController extends BaseController {

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

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

答案 1
<?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";
    }
}

答案 2

对于 laravel 5.x:

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

推荐