AJAX Request getContent Laravel 5.1 - ajax

$content = $request->getContent();
return \Response::json([
'success' => $content
]);
I don't know how to format it to json in laravel 5.1. I want to use the data but if I use $request->input('name') it is null, it's actually in the controller. If you have another way to get the data it would be much appreciated.

you would have to parse the response in the client-side:
JSON.parse(ajaxResponse)
right now you're only getting a string back from the server

Related

Redirect to another route with data Laravel 5.8

Good day everyone. I am encountering an error in my code. I am trying to redirect to another route and passing data with it.
Controller code:
return redirect()->route('customer.success', compact('data'));
Route:
Route::get('success-customer', 'CustomerController#showSuccess')->name('customer.success');
Blade:
Your assistant: {{Session::get($data['assistant'])}}
Now my error is, it shows the error of undefined data yet I used the compact function.
Answers and advices are highly appreciated!
In laravel 5.8 you can do the following:
return redirect('login')->with('data',$data);
in blade file The data will store in session not in variable.
{{ Session::get('data') }}
You can use this:
return redirect()->route('profile', ['id' => 1]);
To redirect to any controller, use this code
return redirect()->action('DefaultController#index');
If you want to send data using redirect, try to use this code
return Redirect::route('customer.success)->with( ['data' => $data] );
To read the data in blade, use this one
// in PHP
$id = session()->get( 'data' );
// in Blade
{{ session()->get( 'data' ) }}
Check here for more info
TRy this
return Redirect::route('customer.success')->with(['data'=>$data]);
In blade
Session::get('data');

Queuing mail with attachData in Laravel 5.1 / OctoberCMS

The following IS working when I use Mail::send
$email = 'my#email.com';
$name = 'My Name';
$invoice = InvoicePdf::generate($invoice_id); // generates PDF as raw data
Mail::send('mail.template', null, function($message) use ($name, $email, $invoice) {
$message->to($email, $name);
$message->subject('Thank you for your order!');
$message->attachData($invoicePdf, 'invoice.pdf', ['mime' => 'application/pdf']);
});
It works fine and an email is generated with the correct PDF attachment.
However, if I change Mail::send to Mail::queue then I receive the following error:
Unable to JSON encode payload. Error code: 5
/var/www/html/october/vendor/laravel/framework/src/Illuminate/Queue/Queue.php
line 90
If I take the $message->attachData(); line out then it works even with Mail::queue so it seems like the raw data from the attachment is causing issues with the queue but there's nothing in the relevant October or Laravel docs about how to deal with this.
May be its because $invoicePdf data is raw data of PDF file and php can not process that data (attachData) when saving to database.
hmm, alternative you can generate file and then just attach file path to mail and then add to queue.
// generate tempfile name
$temp_file = tempnam(sys_get_temp_dir(), 'inv');
// this pdf is generated by renatio plugin but you can
// use your data and save it to disk
PDF::loadTemplate('renatio::invoice')
->save($temp_file);
Mail::queue('mail.template', null, function($message) use ($name, $email, $temp_file) {
$message->to($email, $name);
$message->subject('Thank you for your order!');
$message->attach($temp_file, ['as' => 'Your_Invoice.pdf', 'mime' => 'application/pdf']);
});
it should work.
#Joseph pointed that in Laravel 5.5 there is mailable which can be used. #Joseph pointed this solution and it seems working so you can also use this solution if your laravel version is >= 5.5
https://laracasts.com/discuss/channels/laravel/sending-email-with-a-pdf-attachment
Thanks #Joseph

How to validate params in REST Lumen/Laravel request?

Route:
$app->get('/ip/{ip}', GeoIpController::class . '#show');
How to validate ip's properly? I've tried to inject Request object in show method, but wasn't able to solve this. I want to stick with REST, so using URL parameters is not solution for me. I use it for API purposes, so status code as response would be appropriate.
Also tried that way:
$app->bind('ip', function ($ip) {
$this->validate($ip, [
'ip' => 'required|ip',
]);
});
EDIT:
The answer below is correct, I've found more info about requests in documentation:
Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.
In other words, you cannot use custom requests via injection in constructors in Lumen.
The validate method takes the request object as the first parameter. Since you're passing the ip in the route, you need to create a custom validator.
public function show($ip)
{
$data = ['ip' => $ip];
$validator = \Validator::make($data, [
'ip' => 'required|ip'
]);
if ($validator->fails()) {
return $validator->errors();
}
return response()->json(['All good!']);
}
Edit : This is all laravel does under the hood. You could basically you this function directly to validate the ip and save a lot of effort.
protected function validateIp($ip)
{
return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}

How to write on route to receive request from external laravel project

$client = new Client();
$response =
$client->GET('http://XXX.XX.XX.XX/eDeskApi/module/SOMEFUNCTION',
[
'json' => ['foo' => 'bar']
]);
This is how i'm sending a request to external LARAVEL api.
I just want to know what do i need to write in laravel api router to get something return when i send this request.
Currently i have the following code on laravel api router
Route::GET('module/url', 'Nameof Controller#NameOfMethhod');
And in controller looks like:
public function GetApplicationModuleList()
{
echo 'something';
//i want to print the parameter value which i just sent by above mention request.
}
You need to change your request from GET to POST if you want to send some request body there.
Also your function should take an argument of:
Illuminate\Http\Request type.
After that you can access you request body by doing:
$request -> all();

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();

Resources