JackpotK
JackpotK

Reputation: 313

Laravel Event: how to fire and pass value to a listener after a controller method is called

In this case, we have 3 tables:

tasks (task_id, task_title,task_type)
managers (manager_id, manager_title, manager_type)
assigners (task_id, manager_id)

In TaskController.php, I have a store method to create new task

public function store() {  
    $input = Input::all();
    $this->task->create($input);
     return Redirect::route('tasks.index');}

Here's what I want to achieve:

  1. Pass the newly created task value to an event task.created,
  2. Compare the new task title $task->task_title with any $manager->manager_title, if any matches found ($task->task_title LIKE $manager->manager_title), then pass the matched $task->task_id and $manager->manager_id as an array to another event,
  3. In an event listener located in start/global, it will create new record(s) in assigners table with values received from step2.The event listener is written as below:

    Event::listen('task.created',function($param1,$param2){  
        $new_assigner = new Assigner;  
        $assigner->task_id = $param1;  
        $assigner->manager_id = $param2;  
        $new_assigner->save();  
    });
    

My questions:

  1. Where to fire the event in step 1 (in TaskController?) and what parameter should be used as a value to pass ($this->task?)
  2. How to achieve step 2? (there maybe more than one matches found)

Upvotes: 0

Views: 7434

Answers (1)

tharumax
tharumax

Reputation: 1261

  1. Since you need newly created task, it should be after the task has been created. May be after this line. You can pass newly created task as it is or, pass the task_id and fetch it in the event listener. But you have grab the task first.

    $task = $this->task->create($input);
    Event::fire('task.created', array($task) );
    
  2. Using for each loop.

    Event::listen('task.created', function($task)
    {
        $managers = getManagersForThisTask($task);
    
        foreach($managers as $manager ){
            Event::fire('task.created_step2', $task, $manager );
        }
    });
    

Upvotes: 2

Related Questions