I come across a situation in Laravel while calling a store() or update() method with Request parameter to add some additional value to the request before calling Eloquent fu
I tried $request->merge($array)
function in Laravel 5.2 and it is working perfectly.
Example:
$request->merge(["key"=>"value"]);
Based on my observations:
$request->request->add(['variable' => 'value']);
will (mostly) work in POST, PUT & DELETE methods, because there is value(s) passed, one of those is _token
. Like example below.
<form action="{{ route('process', $id) }}" method="POST">
@csrf
</form>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
But [below code] won't work because there is no value(s) passed, it doesn't really add.
<a href='{{ route('process', $id) }}'>PROCESS</a>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
public function process($id){
$request = new Request(['id' => $id]);
}
Or you can use merge
. This is better actually than $request->request->add(['variable' => 'value']);
because can initialize, and add request values that will work for all methods (GET, POST, PUT, DELETE)
public function process(Request $request, $id){
$request->merge(['id' => $id]);
}
Tag: laravel5.8.11
You can add parameters to the request from a middleware by doing:
public function handle($request, Closure $next)
{
$request->route()->setParameter('foo', 'bar');
return $next($request);
}
Usually, you do not want to add anything to a Request object, it's better to use collection and put() helper:
function store(Request $request)
{
// some additional logic or checking
User::create(array_merge($request->all(), ['index' => 'value']));
}
Or you could union arrays:
User::create($request->all() + ['index' => 'value']);
But, if you really want to add something to a Request object, do this:
$request->request->add(['variable' => 'value']); //add request
The best one I have used and researched on it is $request->merge([]) (Check My Piece of Code):
public function index(Request $request) {
not_permissions_redirect(have_premission(2));
$filters = (!empty($request->all())) ? true : false;
$request->merge(['type' => 'admin']);
$users = $this->service->getAllUsers($request->all());
$roles = $this->roles->getAllAdminRoles();
return view('users.list', compact(['users', 'roles', 'filters']));
}
Check line # 3 inside the index function.
You can also use below code
$request->request->set(key, value).
Fits better for me.