Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to Request object in laravel 5

I have store method in user controller like this

public function store(Request $request)
{
    User::create($request->all()); 

}

and in another controller I want use this method

 public function test(Request $request)
{
  .....
   app('\App\Http\Controllers\UserController')->store($test_array);
  ...
}

and $test_array is:

{"name":"test","email":"[email protected]"}

and finally show me error this

Argument 1 passed to App\Http\Controllers\UserController::store() must be an instance of Illuminate\Http\Request,

How can I convert array to Request object?

like image 676
paranoid Avatar asked May 02 '16 05:05

paranoid


4 Answers

Just use

$request = new Illuminate\Http\Request($test_array);
like image 54
KShport Avatar answered Oct 26 '22 09:10

KShport


How can I convert array to Request object?

If you really want to do it this way, which I wouldn't, here you're:

Something like this should do the trick -- I did not test it:

use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\ParameterBag;
use Illuminate\Http\Request as IlluminateRequest;


$symfonyRequest = SymfonyRequest::createFromGlobals();

$symfonyRequest->query = new ParameterBag([
    'foo' => 'bar',
]);

$request = IlluminateRequest::createFromBase($symfonyRequest);
like image 28
jakub_jo Avatar answered Sep 19 '22 04:09

jakub_jo


use $request->merge($someArray)

You can try this way..

Your second controller's test method.

public function test(Request $request)
{
  $another_array = [];
  $another_array['eg'] = $test_array;
  $request->merge($another_array);

  .....
   app('\App\Http\Controllers\UserController')->store($request->get('eg'));
  ...
}

Your$test_arraymust be of the type array

Hope this will solve your problem.

like image 8
Parvez Rahaman Avatar answered Oct 26 '22 11:10

Parvez Rahaman


I don't think you'll be able to use store() this way.

If you're calling store() action from other places, you could place persisting logic into a model:

class User extends Model

    public function storeData($data)
    {
        $createdUser = User::create($data);
        return $createdUser;
    }

And then call this from store() action and test().

If not just, just change store() to:

public function store($data)
{
    User::create($data); 
}
like image 1
Alexey Mezenin Avatar answered Oct 26 '22 09:10

Alexey Mezenin