I am grabbing the values from the parameters in the URL domain.com?para=value in the controller using
Input:all()
Is there a way to add more values to the Input:all() in the controller?
I have tried $_POST['para'] = "value and $_GET['para'] = "value" but no luck.
I've gone through the docs but cannot find anything.
Thanks
More Info
Here is what is returned
{
"param_1" => "value",
"param_2" => "value",
"param_3" => "value",
}
I would like to add another param into the Input:all()
{
"param_1" => "value",
"param_2" => "value",
"param_3" => "value",
"NEW_PARAM" => "NEW VALUE",
}
In laravel 5, you can use
Request::merge(['New Key' => 'New Value']);
or by using request() helper
request()->merge(['New Key' => 'New Value']);
You should never need to add anything to Input. You should assign Input like so...
$arr = Input::all();
And then add to $arr like so...
$arr['whatever'] = 'whatever';
If you need to get that value in another part of the stack, try to pass it through yourself.
Cheers.
Best way to add data into the input::all() in laravel.
Solution 1
add Request package at the top of the page.
use Request;
Then add following code into your controller.
Request::merge(['new_key' => 'new_value']);
Solution 2
You can assign all the Input::all(); to a variable and then you can add new data to the variable. Like below.
$all_input = Input::all();
$all_input['new_key'] = 'new_value';
Add an input value on the fly inside a request instance
public function store(Request $request){
$request->request->add(['new_key' => 'new_value']);
}
Remove data from an input value on the fly inside a request instance
public function store(Request $request){
$request->request->remove('key');
}
Related
I want to use laravels FormRequest to validate before updating some fields. This works fine if i just use:
User::find($application->userid)->fill($request->only('first_name'...
but the request also contains sub array ($request->programmeData).
array:2 [▼
"programme_id" => 5
"programme_title" => "some programme title"
]
if i try access that the same way i get 'Call to a member function only() on array':
Course::find($application->userid)->fill($request->programmeData->only('programme_id...
I've tried a handful of things, but not sure best way to go with this?
Update
I'm now using a foreach loop to save two items in the array. the example below saves the second value for both user_ids. any reason this isn't saving the first value for the first user_id?
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->get()[$key]->fill(Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']))->save();
}
but nothing updates. Any ideas on this one?
You can use Array::only() helper for this:
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->first()->fill([
$key => Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id'])
])->save();
// or
$course = Course::where('application_id', $application->id)->first()
$course->$key = Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']);
$course->save();
}
//Arr::only($request->programmeData, ['programme_id', ...]);
I have an input like below.
array:4 [
"_token" => "evktHCfCNZVQMNYXzntfHZkdNLZFqvOoYgU3yPKy"
"name" => "Name"
"orderId" => "5cb5943a6733a1555403834"
"amount" => null
]
which I stored to a session like this:
public function store(Request $request)
{
request()->session()->put('bookingInfo', $request->input());
return redirect()->route('book.checkout');
}
Now I want to change the amount value in the session. How I am going to achieve that?
To update the value, you need to retrieve the values from session and update it again.
To do that, you need to do
$booking_info = $request->session()->get('bookingInfo');
Then you will got an array back. Update it like a normal array
$booking_info["amount"] = 10; // anything you wanted
If you need to put it back into session again you can do this
$request->session()->put('bookingInfo', $booking_info);
EDIT
If you want the ability to update partially, you would need to store it separately like this.
$input = $request->all();
$request->session()->put('bookingInfo.name', $input['name']);
$request->session()->put('bookingInfo.orderId', $input['orderId']);
$request->session()->put('bookingInfo.amount', $input['amount']);
Laravel 5+
// Via a request instance...
$request->session()->put('amount', 'value');
// Via the global helper...
session(['amount' => 'value']);
// For retrieve
session('amount');
I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;
In laravel, we can get the input value via Input::get('inputname'). I try to change the value by doing this Input::get('inputname') = "new value";. But then, I get the error message saying Can't use function return value in write context.
Is it possible for us change the input value so that when later calling on Input::get('inputname') will get the new amended value?
Thanks.
You can use Input::merge() to replace single items.
Input::merge(['inputname' => 'new value']);
Or use Input::replace() to replace the entire input array.
Input::replace(['inputname' => 'new value']);
Here's a link to the documentation
If you're looking to do this in Laravel 5, you can use the merge() method from the Request class:
class SomeController extends Controller
{
public function someAction( Request $request ) {
// Split a bunch of email addresses
// submitted from a textarea form input
// into an array, and replace the input email
// with this array, instead of the original string.
if ( !empty( $request->input( 'emails' ) ) ) {
$emails = $request->input( 'emails' );
$emails = preg_replace( '/\s+/m', ',', $emails );
$emails = explode( ',', $emails );
// THIS IS KEY!
// Replacing the old input string with
// with an array of emails.
$request->merge( array( 'emails' => $emails ) );
}
// Some default validation rules.
$rules = array();
// Create validator object.
$validator = Validator::make( $request->all(), $rules );
// Validation rules for each email in the array.
$validator->each( 'emails', ['required', 'email', 'min: 6', 'max: 254'] );
if ( $validator->fails() ) {
return back()->withErrors($validator)->withInput();
} else {
// Input validated successfully, proceed further.
}
}
}
If you mean you want to overwrite input data, you can try doing:
Input::merge(array('somedata' => 'SomeNewData'));
Try this,it will help you.
$request->merge(array('someIndex' => "yourValueHere"));
I also found this problem, I can solve it with the following code:
public function(Request $request)
{
$request['inputname'] = 'newValue';
}
Regards
I'm using Laravel 8.
The following is working for me:
$request->attributes->set('name', 'Value');
I used Raham's answer to solve my problem. However, it was nesting the updated data within an array, when I needed it at the same level as other data. I used:
$request->merge('someIndex' => "yourValueHere");
A note other Laravel newbies, I used the merge method to account for an empty checkbox value in a Laravel 7 update form. A deselected checkbox on an update form doesn't return 0, it doesn't set any value in the update request. As a result that value is unchanged in the database. You have to check for a set value and merge a new value if nothing exists. Hope that helps someone.
Just a quick update. If the user doesn't check a box and I need to enter a value in the DB I do something like this in my controller:
if(empty($request->input('checkbox_value'))) {
$request->merge(['checkbox_value' => 0]);
}
I have some code that should be deleting a record from an embedded MongoDB document.
Here is the code:
public function actionDeleteSaved()
{
$savedLink = $_POST['savedLink'];
$userId = Yii::app()->user->getId();
$current = SaveLink::model()->findByPk($userId);
if(in_array($savedLink, $current->links))
{
array_slice($current->links, $savedLink);
$current->save();
}
}
This is what is passing the data to the controllers action method:
echo CHtml::ajaxButton(
'delete',
Yii::app()->createUrl("dashboard/index/deletesaved"),
array( // ajax options
'type' => 'POST',
'context' => "js:this",
'data' => array(
'savedLink' => $savedLink
)
),
array( //html options
'class'=>'deleteSaved'
)
);
This is what renderPartial looks like:
$this->renderPartial('_deleteSaved', array('savedLink'=>$s));
What I want being posted is being posted correctly but I'm not sure if it's communicating with the Controller and passing the data through or if my code for removing the data from the database is correct.
Any help would be greatly appreciated, thanks.
The problem is with array_slice part. As specified in php docs array slice does not modify array parameter.
Use array_splice instead (it modifies passed array param) and array_search to get key:
if(in_array($savedLink, $current->links))
{
$key = array_search($savedLink, $current->links);
array_splice($current->links, $key, 0);
$current->save();
}
NOTE: If $current->links is embedded documents (objects) array, you might have to find $key and check if is in array some other way.