0

I am trying to add a if condition when resource auto generates.

When I run php artisan make:controller SomeController -r, I want to generate the following,

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{
           //
        }
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Aushraful
  • 132
  • 1
  • 7
  • you might have to look into custom generators so you can define the stub file you want to use to generate the controller ... if you actually want a custom controller made like that – lagbox Nov 20 '19 at 07:43

1 Answers1

2

Try to use middleware to do this, See: 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 ...']);
        }

    }
}

Defined your route Middleware in app/Http/Kernel.php:

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

And use middleware in route.

Route::group(['middleware' => 'AuthCan'], function(){
    Route::get('/', 'SomeController@index');
    Route::get('/{id}', 'SomeController@show');
    ...
}
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28