Adam nick Adam nick - 1 month ago 10
PHP Question

handle multiple post requests to same url Laravel 5

I have two forms on a page both submits the data via

POST method
. I want to handle both requests on the same url i.e /home and use different controllers and methods for both forms. Below are the two routes.

Route::post('home' ,'FacebookControllers\PostsController@save');
Route::post('home' , 'FacebookControllers\MessageController@storeMessage');


In
PostsController@save
I am checking

if(isset($_POST['submitPost']) && $_SERVER['REQUEST_METHOD']=='POST'){
//do something
}


and in
MessageController@storeMessage
I am doing the same for other form

if(isset($_POST['sendMessage']) && $_SERVER['REQUEST_METHOD']=='POST'){
return "got it";
}


The problem is that only second route works. I don't if I am doing right or wrong. Please lead me to the right direction.

Answer Source
Route::post('home' ,'FacebookControllers\PostsController@save');
Route::post('home' , 'FacebookControllers\MessageController@storeMessage');

won't work - how should laravel determine where to post to? The way I would go is to create two jobs and one route, then check for the value in Request and dispatch the correct job.

First, create two job classes with

php artisan make:job FacebookSave
php artisan make:job FacebookStoreMessage

The generated file will look much like this:

<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;

class FacebookSaveMessage extends Job implements SelfHandling
{
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
    }
}

In the job's handle() method you can do what you wanted to do in your Controller.

Now the route, let's do

Route::post('home' ,'FacebookControllers\PostsController@findAction');

and according to this in your PostsController, add a method (I called it findAction) like this:

public function findAction(\Illuminate\Http\Request $request) {
    if ($request->has('submitPost')) {
        return $this->dispatch(new \App\Jobs\FacebookSave($request));
    } else if ($request->has('storeMessage')) {
        return $this->dispatch(new \App\Jobs\FacebookStoreMessage($request));
    }
    return 'no action found';
}

This way the correct action will be performed depending on the submitted value.

Change the job's constructor to something like:

public function __construct($data)
    {
        $this->data = $data;
    }

And you can access the submitted values from the forms you have submitted inside the job's handle() method with $this->data