In laravel to get the request data we use request class or function but sometimes we want to add values to request array in laravel, so to add extra values or we can say to merge to our own custom values to laravel request array we need to use merge
method of request class.
In this article i will show you to add extra values to request using merge method and also we will cover to add array values in existing request.
We will use simple example and multiple methods to add values to existing request class. this example will work with any laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.
Suppose we have a request form and we want to add user_id
key to $request variable in laravel so to achieve this we can simply use as follow
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$request->merge(["user_id"=>1]);
}
}
so here we used $request->merge(["user_id"=>1]);
to merge the user id field.
Add array of data to request in laravel
As we can see above we easily added the extra params to request and now in the same way we can add array in request as follow
$request->merge(["user_id"=>["a"=>"1","b"=>3]]);
so complete controller
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$request->merge(["user_id"=>["a"=>"1","b"=>3]]);
}
}
Screenshot:
Updating array field of request in laravel
Let’s suppose we have a form which consist form array and we want to update or add some values to array field then we can even use same merge request but before merge we need to extract it and then we will modify the array. suppose we have multiple ids
in array request as follow
[1,2,3] // form field user_ids
then if we want to add more data to it then we need to extract it from request array first
$userids = $request->user_ids;
$userids[]=4;
$userids[]=5;
now merge it with old request as follow
$request->merge(["user_ids"=>$userids]);
Also Read : How to Get Headers Data from Request in Laravel ?