skip to Main Content

I need to create a user accreditation controller. Users can be of two types: Buyer and Seller. I want different controllers to be called at the same address /accreditations/create depending on the type of user.
Now I did this.

Route web.php
Route::middleware('auth')->group(function () {
    Route::resource('accreditations', AccreditationController::class);
});

In the Create method of the AccreditationController

public function create()
{
    $user = auth()->user();

    $controllerName = $this->getControllerName($user->role);
    $controller = app()->make($controllerName);
    return $controller->callAction('create', []);
}

protected function getControllerName($id){
     return match ($id) {
         Roles::TRADER=> TraderController::class,
         Roles::BUYER => BuyerController::class,
     };
 }

Accordingly, in each controller I made a Create method that calls its own View

class TraderController extends Controller
{
    public function create()
    {
        $user = auth()->user();
        return View('Accreditations/CreateTrader', compact('user'));
    }
}

Am I doing the right thing or is there a better way to solve this problem?

2

Answers


  1. so your case is : you have 2 roles (buyer and seller) and you want your action is depent by roles ?

    maybe just need 1 controller and if condition.
    so your controller will be like this :

    public function create(){
      if(role=="buyer"){
        //code for buyer
      }
      else{
        //code for seller
      }
    }
    
    Login or Signup to reply.
  2. Changing what @Herry’s answer, you can do

    public function create(Request $request){
      $user = auth()->user();
      if($user->role=="buyer"){
        return $this->createBuyer($request);
      } else if($user->role=="seller"){
        return $this->createSeller($request);
      } else{
        return $this->createDefault($request);
      }
    }
    
    public function createBuyer($request) {
      
    }
    
    public function createSeller($request) {
      
    }
    
    public function createDefault($request) {
      
    }
    

    Where you have a single point of entry method create then return methods based on the role. Another pro for this way is you can extend as much on the if/else without too much git noise. If both buyer and seller has the same parts of the code that they run, you can create new method or traits then add them inside the method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search