Redirect response data to another view - laravel

im trying in my controller method to pass some data to a order sucess page, information regarding the details of payment, but i cant make it work or pass the data.
In my case i wish for example pass this request
$http = new \GuzzleHttp\Client;
$response = $http->request('POST', 'https://domain', [
'form_params' => [
'chave' => 'somekey',
'valor' => Cart::total(),
'id' => $order->id,
]
]);
$result = json_decode((string) $response->getBody(),true);
Cart::destroy();
return redirect()->route('frontend-cart-success')->with( ['data' => $result] );
And then in my view sucess page just calling the $data Info to show on my blade file.
But i cant it ut it work.
My route to pass in sucess page:
Route::get('cart/success/', 'Frontend\CartController#showSuccess')->name('frontend-cart-success');
Best regards

I code mostly in SPAs, but according to the API (https://github.com/laravel/framework/blob/5.7/src/Illuminate/Http/RedirectResponse.php#L42), it's flashing that data to the session, so you're going to have to get the data back out using the session.
See: https://laracasts.com/discuss/channels/laravel/redirect-to-route-with-data?page=1

Related

Can't get data from Auth::user()

I am new to Laravel.
I am using external API into login page
So I use this into login controller
note : $userId, $nama are data I get from external API, and I want it to store in Auth.
$user = [
'id' => $userId,
'nama' => $nama,
'prodi' => $prodi,
'email' => $email,
'nidn' => $nidn,
'nip' => $nip,
'jabatanFungsional' => $jabatanFungsional,
'keaktifan' => $keaktifanDosen
];
$user = new AuthUser($user);
Auth::login($user);
return view('pages.biodata');
in view biodata, I use this code and that works
{{ auth()->user()->nama }}
but when I go to another view where code
{{ auth()->user()->nama }}
is still using, I got error:
Attempt to read property "nama" on null
even though I still don't use syntax Auth::logout()
Can some one tell me what is wrong?
I want to login using external API, and get data from that so I can pass that data to my view using Auth::user()->somedata.
For first return view from controller, I can do Auth::user()->nama and display a text, but when I go to another view and using Auth::user()->nama, an error Attempt to read property "nama" on null displays.

how can i send http post requests from Laravel to Strapi CMS via Strapi's API

I tried sending post requests to the API in postman and it works fine. but i can't find a proper syntax of doing from Laravel, i tried following this tutorial from the Laravel documentation Http-client so i tried this syntax
function sendRequest (Request $data) {
$phonenumber = $data['number'];
$name = $data['name'];
$data2['data']['attributes'] = [
[
'phonenumber' => $phonenumber,
'name' => $name
]
];
Http::post('http://example.com/users', $data2);
}
didn't work.
here is the API's data structure
thanks in advance
I do not know if this will make a difference but you're missing a comma after value2 as per the syntax.
$response = Http::post('http://example.com/users', [
'name' => 'Steve',
'role' => 'Network Administrator', ]);
I'm rather new to laravel also and id love to know this fix too incase I need it in the future :D good luck!

How to validate inputs from GET request in Laravel

I wanted to validate inputs from a GET request without using the
this->validate($request... or \Validator::make($request...
and prefer to do it like
$input = $request->validate([... rules ...]);
however since get requests doesn't have $request parameters how can I achieve it?
public function sampleGet($param1, $param2) {
// How can I pass the $param1 and $param to to validate?
$input = $request->validate([
'param1' => 'required',
'param2' => 'required
]);
}
You can do so and it will have same behavior as validate
validator($request->route()->parameters(), [
'param1' => 'required',
'param2' => 'required'
....
])->validate();
If you want all the route parameters you can get them as an array:
$request->route()->parameters()
Since you already have those parameters being passed to your method you can just build an array with them:
compact('param1', 'param2');
// or
['param1' => $param1, 'param2' => $param2];
You are not going to be using the validate method on the Request though, you will have to manually create a validator. Unless you want to merge this array into the request or create a new request with these as inputs.
There is nothing special about the validate method on a Controller or on a Request. They are all making a validator and validating the data the same way you would yourself.
When manually creating a validator you still have a validate method that will throw an exception, which would be the equivalent to what is happening on Request and the Controller with their validate methods.
Laravel 7.x Docs - Validation - Manualy Creating Validators - Automatic Redirection
You can do like that.
public function getData(Request $request)
{
try {
$input['route1'] = $request->route('route1');
$input['route2'] = $request->route('route2');
$valid = Validator::make($input, [
'route1' => 'required',
'route2' => 'required'
]);
} catch (\Throwable $th) {
echo "<pre>";print_r($th->__toString());die;
}
}
Or you can follow the below link for more info.
https://laravel.com/docs/7.x/validation#manually-creating-validators

Laravel:Method ...Controller::show does not exist

I'm trying to validate post request. I think when the validation fails, it gives me this error message.
app/Http/Controllers/InternationalShippingController.php
public function store(Request $request){
//echo '<pre>';
$post = $request->post();
$order_ids = session('international_order_ids');
//var_dump($order_ids);
//var_dump($post);
$validator = Validator::make(
$post,[
'documents.*' => 'mimes:jpg,jpeg,png,pdf|max:5000|nullable',
'company_name' => 'nullable',
'shipping_address1' => 'nullable',
'message' => 'size:1000',
],[
'image_file.*.mimes' => __('Only jpeg,png and pdf files are allowed'),
'image_file.*.max' => __('Sorry! Maximum allowed size for an document is 5MB'),
]
);
if($validator->fails()){
return redirect('internationalshippings/create2')
->withErrors($validator)
->withInput();
}
}
web.php
Route::post('internationalshippings/create2','InternationalShippingController#create2');
Route::resource('internationalshippings','InternationalShippingController');
I haven't made show() method in the controller.
Does this error mean when the validation fails, it tries to redirect to internationalshippings/show method?
When the validation fails,I'd like this to redirect back to internationalshippings/create2. How can I achieve this?
Thank you
you are using the resource controller,
in resources this url internationalshippings/SomeThing means the show method i mean this url calls the show method in resource
First way
so you can use this in your fail return:
return redirect()->route('your_route_name') OR return back()
Second way
and the second way is in your web.php, when you are defining the resource route, type in this way:
Route::resource('internationalshippings','InternationalShippingController',['except'=>['show']]);
EDIT:
in your code situation the best way is change Return, because the url that you want to redirect to it, is POST

Validate POST request Laravel?

I validate POST request like:
$validator = Validator::make($request->all(), [
"id.*" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json($validator->errors, 400);
}
echo "Ok";
When I send request without parameter id it skips validation and returns echo "Ok";.
Why validation does not work?
If you expect id is array of integers you should update validation rules like this:
$validator = Validator::make($request->all(), [
"id" => 'required|array',
"id.*" => 'integer'
]);
First know when using $request->validate(); when it fail exceptions are raised!
And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.
To note, when using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.
<?php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
And there is no better then the doc itself: https://laravel.com/docs/5.7/validation
there is a lot of options, to personalize our validation process.

Resources