How to change value of a request parameter in laravel - laravel

I need to change value of my request parameter like this:
$request->name = "My Value!";
I use this code but does not work:
$request->offsetSet('img', $img);

Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to #JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request

Use merge():
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all() to another variable.
Read more about Laravel's merge() here:
https://laravel.com/docs/collections#method-merge

If you need to customize the request
$data = $request->all();
you can pass the name of the field and the value
$data['product_ref_code'] = 1650;
and finally pass the new request
$last = Product::create($data);

If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);

Use add
$request->request->add(['img' => $img]);

If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().
namespace App\Http\Requests\Admin\Category;
class CategoryRequest extends AbstractRequest
{
protected function prepareForValidation()
{
if ( ! $this->get('url')) {
$this->merge([
'url' => $this->get('name'),
]);
}
$this->merge([
'url' => \Str::slug($this->get('url')),
'active' => (int)$this->get('active'),
]);
}
}
I hope this information will be useful to somebody.

It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2

Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);

Try that :
$request["name"] = "My New Value";
$request["img"] = $img;
It's worked in Laravel 8.

Also, make sure to update the model class.
Item
{
fillable=[
'img',
... // other attributes
];
}

in case of updating an item of object you can write the lines bellow
$Obj = $request->data;
$Obj['item'] = value;

Related

Laravel: Is it possible to directly test the json response output of a function without actually going through the URI?

From the docs, I can test some json returned from my app using the following:
$response = $this->json('POST', '/user', ['name' => 'Sally']);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
However, is it possible to bypass actually calling up the URI with $this->json(*method*, *uri*, *data*); and instead test the direct output of a controller function which returns json? For example, I want to do something like this:
// My controller:
function getPageData(){
$data = array('array', 'of', 'data');
return response()->json($data);
}
// My Test Class:
$controller = new Primary();
$response = $controller->getPageData();
$response->assertJson([
'array', 'of', 'data'
]);
Is this possible?
You could do this for some basic methods, but it might cause side effects:
app(SomeController::class)->someControllerMethod();
Basically, the app() will resolve the dependencies from the constructor, but it won't resolve the method dependencies. So if you typehint something like method(Request $request), it will throw an error.
I'm pretty sure dealing with request() will cause unintentional effects since there's no real request going on.
Edit:
You could then create a TestResponse object, to get all the asserts as well:
$res = app(SomeController::class)->someControllerMethod();
$testRes = new Illuminate\Foundation\Testing\TestResponse($res);
$testRes->assertJson(...); // Will be available

Passing variable from DOMPDF controller to view

I want create a DOMPDF with laravel, and I must passing my variable to view. I've been try passing variable like below, but it still not working yet.
here my Laravel Controller
public function pdf(Request $request, $id){
$salesorder = $this->show($id)->salesorder;
$detailservice = $this->show($id)->detailservice;
$detailemployee = $this->show($id)->detailemployee;
$data = [$salesorder, $detailemployee, $detailservice];
$pdf = PDF::loadView('summary.invoice', $data);
return $pdf->download('invoice.pdf');
}
the error on my view is :
Undefined variable: salesorder
How to passing some variable from Laravel controller to DOMPDF ?
PS : dd($data) result is correctly
You have to pass the data as below
$data = [
'salesorder' => $salesorder,
'detailemployee' => $detailemployee,
'detailservice' => $detailservice
];
or try using compact
$data = compact('salesorder', 'detailemployee', 'detailservice');
You may try this following
public function pdf(Request $request, $id){
$salesorder = $this->show($id)->salesorder;
$detailservice = $this->show($id)->detailservice;
$detailemployee = $this->show($id)->detailemployee;
$pdf = PDF::loadView('summary.invoice', array('salesorder' => $salesorder,'detailemployee'=>$detailemployee,'detailservice'=>$detailservice));
return $pdf->download('invoice.pdf');
}
You can use library function to do that easily.
$pdf_text = "It will be the text you want to load";
PDF::loadHTML($pdf_text)->save('public/you-file-name.pdf');
You can change the orientation and paper size, and hide or show errors (by default, errors are shown when debug is on)
PDF::loadHTML($pdf_text)->setPaper('a4', 'landscape')->setWarnings(false)->save('public/you-file-name.pdf')
You may try the following.
$html = view('summary.invoice', ['salesorder' => $salesorder, 'detailemployee' => $detailemployee, 'detailservice' => $detailservice])->render();
$pdf = App::make('dompdf.wrapper');
$invPDF = $pdf->loadHTML($html);
return $pdf->download('invoice.pdf');
I know this is old but this may help others. you need to use array key in your view.
Controller:
$data = [
'foo' => $bar,
];
$pdf = PDF::loadView('pdf.document', $data);
return $pdf->stream('doc.pdf');
View:
<p>{{$foo}}</p>

How to redirect user invoking a function in contoller Class? - Laravel

I want user to get calculated result. I had to redirect localhost:8000/question/33 to localhost:8000/caclulate/some_payload
I have no idea how to do this.
class QuestionController extends Controller
public function index($id)
if(question->id == 33)
#Here I want to invoke calculate($payload)
return view('quiz.index', [
'payload' => $payload,
'question' => $question,
]);
}
public function calculate($payload)
{
return view('quiz.result', [
...
]);
}
I've tried $this->calculate($payload) and calculate().
If I understand right, you want call controller method from another controller method.
You could try it this way:
$request = Request::create('calculate/some_payload', 'GET', $params);
return Route::dispatch($request)->getContent();
For more info see Jason Lewis answer here: Consuming my own Laravel API
Are you expecting Request::json () to provide form input? Or, are you looking for Input::all() form input?
I've solved, my problem with:
return Redirect::action('QuestionController#calculate',
array('payload' => $payload));
But it generates address with parameter
http://localhost:8000/calculate?payload=%242y%2410%24V1OqC7rwp1w1rPXYQ42lRO9lJYQvmXB3nScw6D0EVeFR7VUz0QyCS
And I want to use$_POST instead of $_GET, so I need to invoke method with $_POST and catch $payload in method calculate. How can I do this?

Laravel testing, get JSON content

In Laravel's unit test, I can test a JSON API like that:
$this->post('/user', ['name' => 'Sally'])
->seeJson([
'created' => true,
]);
But what if I want to use the response. How can I get the JSON response (as an array) using $this->post()?
Proper way to get the content is:
$content = $this->get('/v1/users/1')->decodeResponseJson();
Currently, in 5.3 this is working...
$content = $this->get('/v1/users/1')->response->getContent();
However, it does break the chain since response returns the response and not the test runner. So, you should make your chainable assertions before fetching the response, like so...
$content = $this->get('/v1/users/1')->seeStatusCode(200)->response->getContent();
As at Laravel 8, this worked for me.
I was returning an automatically generated field (balance) after the POST request has created the entity.
The response was in the structure {"attributes":{"balance":12345}}
$response = $this->postJson('api/v1/authors', [
'firstName' => 'John',
'lastName' => 'Doe',
])->assertStatus(201);
$balance = $response->decodeResponseJson()['attributes']['balance'];
decodeResponseJson will pick the response and transform it to an array for manipulation.
Using getContent() returns json and you will have to use json_decode on the returned data to turn it into an array.
I like to use the json method when working with json, instead of ->get()
$data = $this->json('GET', $url)->seeStatusCode(200)->decodeResponseJson();
I hit a similar problem and could not get $this->getResponse()->getContent() working with the built in $this->get() method. I tried several variations with no success.
Instead I had to change the call to return the full http response and get the content out of that.
// Original (not working)
$content = $this->get('/v1/users/1')->getContent();
// New (working)
$content = $this->call('GET', '/v1/users/1')->getContent();
Simple way:
$this->getJson('api/threads')->content()
Just want to share, I have used the same in $this->json() like:
$response = $this->json('POST', '/order', $data)->response->getContent();
But I added one more line to use json response and decode otherwise decodeResponseJson() was not working for me.
$json = json_decode($response);
Found a better way:
$response = $this->json('POST', '/order', $data);
$responseData = $response->getOriginalContent(); // saves the response as an array
$responseData['value'] // you can now access the array values
This method returns the response json as an array.
You can just call:
$data = $response->json();
$response = $this->json('POST', '/products', $data);
$data = $response->getData();

In Codeigniter, how to pass a third parameter to a callback (form validation)?

I am currently using the Form Validation class (on Codeigniter) and setting rules.
It works like this with two parameters (codeigniter.com/user_guide/libraries/form_validation.html):
$this->form_validation->set_rules('username', 'Username', 'callback_test[abc]');
But what about a third parameter? And a fourth...? Is it possible?
It is not official but works
Split the parameter by ','
$this->form_validation->set_rules('article_big_image','Gambar Besar','callback_check_picture[article_big_image,edit]');
function check_picture($image,$param){
$param = preg_split('/,/', $param);
$field = $param[0];
$action = $param[1];
echo $field.$action;
}
Not without extended the system form validation class. For information on how to achieve this take a look at this article.
Alternatively you can access the post variables within your callback function using:
$this->input->post('field_name');
which may or may not help you out.
You can use Array for more parameters for more fields as like i did below:
$error = array(
array(
'field' => 'check', // the field name will come here
'label' => 'Check',
'rules' => 'required|here you can put the callback Function'
)
);
$this->form_validation->set_rules('article_big_image','Gambar','callback_check_picture[article_big_image,edit]');
function check_picture($image,$param){
$param = explode(',', $param);
$field = isset($param[0])?$param[0]:'';
$action = isset($param[1])?$param[1]:'';
echo $field.$action;
}
You can pass to the rule
|callback_handle_is_unique_value_combinations[val1,val2]
than,
public function callback_handle_is_unique_value_combinations($str, $field)
{
$fields = explode(',', $field);
$val1 = $fields[0];
$val2 = $fields[1];
and then you made your cponarisons

Resources