0

我正在尝试if在资源自动生成时添加条件。

当我运行时php artisan make:controller SomeController -r,我想生成以下内容,

class SomeController extends Controller
{
    public function index()
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function create()
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function store(Request $request)
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function show($id)
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function edit($id)
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function update(Request $request, $id)
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
    public function destroy($id)
    {
        if (Auth::user()->can('')){
           //
        }else{
           //
        }
    }
}
4

1 回答 1

2

尝试使用中间件来执行此操作,请参阅:https ://laravel.com/docs/master/middleware

namespace App\Http\Middleware;
use Auth;
use Closure;

class AuthCan {
    public function handle($request, Closure $next)
    {
        if (Auth::user()->can('')){
           //
           return $next($request);
        }else{
           //
           return response()->json(['status' => false, 'code' => 1001, 'msg' => 'Cannot ...']);
        }

    }
}

在以下位置定义了您的路由中间件app/Http/Kernel.php

    protected $routeMiddleware = [
        'AuthCan' => \App\Http\Middleware\AuthCan::class,
    ...

并在路由中使用中间件。

Route::group(['middleware' => 'AuthCan'], function(){
    Route::get('/', 'SomeController@index');
    Route::get('/{id}', 'SomeController@show');
    ...
}
于 2019-11-20T07:01:31.177 回答