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
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 :
Changing what @Herry’s answer, you can do
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 bothbuyer
andseller
has the same parts of the code that they run, you can create new method or traits then add them inside the method.