php – Laravel 6 – One Controller with Multiple Functions-ThrowExceptions

Exception or error:

I have multiple users in my system, so I want a manager User with different dashboard.

My Controller look like this:

-Dashboard
 ->AdminDashboardController
 ->UserDashboardController

In my AdminDashboardController I have 2 function

    public function countAllUser()
    {
        $cards = User::count();

        return response()->json(['cards' => $cards]);
    }

    public function totalSales()
    {
        return 'Hello';
    }

And In My DashboardController Like this

  public function index(Request $request)
    {
        $adminUser = auth()->user()->roles->pluck('name')->toArray();

        if($adminUser[0] === 'administrator') {
            return (new AdminDashboardController())->countAllUser();
        }
    }

yes, its work, but if I tried something like this

return (new AdminDashboardController())->countAllUser()->totalSales();

It doesn’t work and I think this doesn’t make sense either..

Is there a way I can achieve this?? Thanks…

How to solve:

You should create Action/Helper/Service Class but if you want to return controller methods you will need to do something like

return response([
    'user_count' => (new AdminDashboardController())->countAllUser(), 
    'sales' => (new AdminDashboardController())->totalSales(),
]);

Answer´╝Ü

Although call controller method from another controller is not a good practice ,you should use service.

But if you really want to do this , you can do it by

\App::call('App\Http\Controllers\AdminDashboardController@countAllUser');

or

(new AdminDashboardController())->countAllUser();

or

app(\App\Http\Controllers\AdminDashboardController::class)->countAllUser();

Your code

return (new AdminDashboardController())->countAllUser()->totalSales();

didn’t work because
(new AdminDashboardController())->countAllUser() returns a \Illuminate\Http\JsonResponse instance , you should call totalSales on an controller instance

Leave a Reply

Your email address will not be published. Required fields are marked *