laravel simple axios with argument - laravel

I'm trying to set axios request but always getting missing argument, but not sure how can I pass it can someone explain why this wont work?
my route: (web.php)
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
my controller: (Controllers/API/SessionsController.php)
class SessionsController extends Controller
{
public static function setSuccessMessage($key, $value)
{
session()->put($key ,$value);
}...
and my vueJS axios call (resources/assets/components/Login.vue)
created: function () {
// check is user logged out
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'}).then((response)=> {
console.log(response);
})
},

Use :
public static function setSuccessMessage(Request $request)
{
$key = $request->get('message');
$value = $request->get('message2');
session()->put($key ,$value);
}

If you want to send the data as a part of your request body you can do so like
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage/{message}/{message2}', 'API\SessionsController#setSuccessMessage');
If you wish to send the data as a request params (everything after ? in the url) you can do so like this
var params = {
message1: message1,
message2: message2
};
axios.post('/api/setSuccessMessages', {}, {'params': params})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
//You can further use them as such in controller
function public test(Request $request) {
$request->get('message1');
$request->get('message2');
}
I'll reference axios official docs for the axios request params

Related

Axios gives undefined while accessing data at Vue's componenet in Laravel

I'm using Laravel and Vue's component, and when i try to access the banners property from response returned by axios in vue component it gives me undefined.
I am accessing the perperty like response.data.banners
I'm returning data from controller in following way:
public function getBanners(Request $request){
return response()->json(['
banners'=> BannerImage::active()->get()
]);
}
Here is how i am accessing axios response
<script>
export default {
data: function() {
return {
banners: []
}
},
mounted() {
axios.get("getBanners").then((res)=> {
console.log(res);
console.log(res.data);
console.log(res.data.banners);
this.banners = res.data.banners;
});
console.log('Component mounted.')
}
}
</script>
Response by axios
All is working before accessing the banners property. Is there anything i am not doing correct ?
You have an linebreak ↩ between ' and banners, which is shown in the console line 2 "↩ banners":
Problem
public function getBanners(Request $request){
return response()->json([' // <-- ↩ line break
banners'=> BannerImage::active()->get()
]);
}
Correct
public function getBanners(Request $request) {
return response()->json([
'banners' => BannerImage::active()->get()
]);
}

Axios GET with params request shows NULL in Laravel

I am sending some data to my laravel controller using axios get request but the laravel controller shows request null.
my axios request:
const data = {
machine_id: machine_id,
}
const api = "http://192.168.0.108:8000/api/"
const params = JSON.stringify(data)
const headers = {
"Content-Type": "application/json",
}
axios.get(api, { params: params }, headers).then((response) => {
consoleLog("response", response.data)
})
controller:
public function index(Request $request)
{
dd($request->all()); // shows null
}
If I return the response instead of dd() it shows me something like below image:
public function index(Request $request)
{
return $request->all(); // shows data
}
How can I catch the data in controller??
I had the same problem with you. This is what I've done to resolve my problem
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
let params = new UrlSearchParam();
params.append('var1', 'val1');
params.append('var2', 'val2');
//Finally
axios.post('gotourl', params, config).then( ( response ) => {
console.log(response.data);
});

I'm getting two session ids in one session with Laravel

I have a controller called CartController.php
In this controller I have two methods:
public function store(Request $request)
{
// we'll check to see if the order is already in db
$productOrderDetails = new \App\Cart;
$productOrderDetails->session_id = session()->getId();
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
return response()->json($request);
}
public function displayCart()
{
//dd($upsCost);
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
dd($currentSessionID);
session(['inCartDetails' => $displayCart]);
return view('layouts.cart')->with('cartDetails', $displayCart);
}
The store method is hit by a fetch api post.
export async function postProductDetails(details) {
const url = 'http://127.0.0.1:8000/api/cartDetails';
let response = await fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(details)
})
if(response.ok) {
window.location.href = "/cart";
} else {
alert("HTTP-Error: " + response.status);
}
// return response.json();
}
My problem is that I'm getting two different session ids.
When the method store is hit via the fetch post I get the session id:
HnSxCjSXflzyt4Uks3SGsEZcJEHleSR97N1RNA5l
Then when I run the method displayCart it gives me a different session id:
su8A6E3umTW1XmXf5Yhk3SHU5WUGCEpcJWXlnVIP
It's being accessed from same browser, with in a couple of minutes. Any idea why this is happening?
I would not rely on the session ID for your logic, You could however create a Cart and save the Cart ID to the session and then retrieve it:
public function store(Request $request)
{
$productOrderDetails = new \App\Cart;
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
session(['cart_id' => $productOrderDetails->id]);
return response()->json($request);
}
public function displayCart()
{
$displayCart = session('cart_id') ? Cart::find(session('cart_id')) : null;
return view('layouts.cart')->with('cartDetails', $displayCart);
}

Laravel Ajax "GET" keeps resulting in 500 Error

I have already searched the web but most 500 Errors tend to be for the "POST" ajax type.
I am trying to get some data from my server using Ajax method.
My script is as follows
<script type="text/javascript">
function getuserinfo(id) {
var userID = id;
console.log(userID);
if(userID) {
$.ajax({
url: '/guestinfo/ajax/'+userID,
type: "GET",
dataType: "json",
success:function() {
$('#infoModal').modal('show');
}
});
}
};
</script>
My Route is as follows
Route::get('/guestinfo/ajax/{guest_id}','Controller\Control#getInfo');
My controller is as follows
public function getInfo($id)
{
if($request->ajax())
{
$guestid = $id;
$guest = Guest::where('id', '=', $guestid)->firstOrFail();
return json_encode($guest);
}
}
Error log from console
Any help or guidance will be appreciated.
You should use return response()->json($guest); to return json data instead of return json_encode($guest);
And the error is because of the $request is not defined that should be an instance of Request $request in your method.
public function getInfo(Request $request, $id)
{
if($request->ajax())
{
$guestid = $id;
$guest = Guest::where('id', '=', $guestid)->firstOrFail();
return response()->json($guest);
}
}
You should be checking your log files so you can actually see what is causing the 500 error, always.
Just by going off of your code that you have pasted you are trying to use an undefined variable as an object:
$request->ajax()
That variable, $request, is undefined in the scope of that method.

How to get parameter from angular get method in laravel?

I want to return user details from Laravel via Angular http.get() method, but its returning null from laravel.Everything is working fine except http.get() method.
Angular code
app.component.ts
this.userdetailservice.getuserdetails(44).subscribe(
(response) => {
console.log(response);
},
(error) => {console.log(error); }
);
userdetailservice.ts
url = 'http://localhost:8080/laravel_angular/blog/public/api/geteachuserdetail';
constructor(private http: HttpClient) { }
getuserdetails(id: any)
{
const headers = new HttpHeaders().set('Content-type', 'Application/json');
const myparams = new HttpParams();
myparams.set('id', id);
return this.http.get<any>(this.url, { headers: headers, params: myparams});
}
Laravel end
api.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Route::get('/geteachuserdetail', "UserloginController#geteachuserdetail");
UserloginController.php
public function geteachuserdetail(Request $request) {
$id=$request->input('params');
echo json_encode(array('userdetail'=>$id));
}
Try this:
Route::any('/geteachuserdetail', "UserloginController#geteachuserdetail");
and
public function geteachuserdetail(Request $request) {
$id = $request->input('params');
return response()->json(array('userdetail' => $id));
}
And you can try request you api with other tools like Postman, look the response code and the response content.

Resources