Search code examples
phplaravelredislaravel-controller

Call a Controller method from a Command in Laravel


I have a Command that is listening via Redis Pub/Sub. When a Publish is received, I want to call a controller method so that I can update the database.

However, I have not been able to find any solution on how to call a controller method with parameters from inside of the project but outside of the routes. The closest thing I have seen is something like:

    return redirect()->action(
        'TransactionController@assignUser', [
               'transId' => $trans_id,
               'userId' => $user_id
        ]);

My complete command that I've tried looks like this:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RedisSubscribe extends Command
{

    protected $signature = 'redis:subscribe';

    protected $description = 'Subscribe to a Redis channel';

    public function handle()
    {
        Redis::subscribe('accepted-requests', function ($request) {

            $trans_array = json_decode($request);
            $trans_id = $trans_array->trans_id;
            $user_id = $trans_array->user_id;

            $this->assignUser($trans_id, $user_id);
        });
    }

    public function assignUser($trans_id, $user_id)
    {
         return redirect()->action(
            'TransactionController@assignUser', [
               'transId' => $trans_id,
               'userId' => $user_id
            ]);
    }
}

However, this does not seem to work. When I run this Command, I get an error that assignUser() cannot be found (even though it exists and is expecting two paramters). I am also not sure a "redirect" is really what I am after here.

Is there some other way to call a controller function in a Command, or some other way that would make this possible to do?


Solution

  • If your controller does not have any required parameters, you can just create the controller as a new object, and call the function.

    $controller = new TransactionController();
    $controller->assignUser([
               'transId' => $trans_id,
               'userId' => $user_id
            ]);