I'm getting two session ids in one session with Laravel - 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);
}

Related

Laravel: return data from server without redirect

What I'm trying to do is call function form server and validate data in javascript function but the return statement from server make redirect before response.complete("success")
button.onclick = async function handlePurchase() {
const payment = new PaymentRequest(methods, details, options);
try {
const response = await payment.show();
// Call server logic here and validate response if OK continue
// But server response redirect here so code not completed
$('#checkout-form').submit();
$.ajax({
url: '{{route("apple-pay")}}',
type: 'post',
data: $('#checkout-form').serialize(),
success: function(data){
console.log('data :>> ', data);
}
});
await response.complete("success");
// redirect to success page
} catch (err) {
console.error("Uh oh, something bad happened", err.message);
}
}
Server function:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return $respone->json();
}
Seperate the request you are making to the third party app and the response you are sending back to you ajax call. This is how I mean:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return response()->json([
'success' => $response->ok() ? 1 : 0,
...
]);
}
Check the last line in the controller it says "return $respone->json();" and should be "return $response->json();" -- missing the "s" in response.

How do I update an existing entry in my database?

How can I update my database properly? I'd like to modify an entry for which I have the id for, but a 'net::ERR_EMPTY_RESPONSE' is returned. Below I have my Controller:
public function update(Request $request, $id)
{
$booking = Booking::query($id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
These are all defined in my home blade view:
const eventData = {
id: eventid,
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
How do I properly update start_date and end_date in my database?
Additionally, this is my Javascript used to fetch:
const eventid = arg.event.id;
const eventData = {
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
console.log(csrfToken);
fetch(`/api/event/update/${eventid}`, {
method: 'PUT',
headers: {
"X-CSRF-Token": csrfToken
},
body: encodeFormData(eventData),
})
.then(response => console.log(response))
.catch(error => console.log(error));
console.log("Complete");
I'm not sure how you're passing the ID for the booking, but from what I can see on the above, the ID is being passed in the request. Try this:
public function update(Request $request)
{
$booking = Booking::findOrFail($request->id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
Updating a record is straight forward all you've got to is
public function update(Request $request)
{
// find the record by it's ID and also update it on the fly if you don't need to process anything else
$updatedData = Booking::findOrFail($request->id)->update(['start_date' => $request->start, 'end_date' => $request->end]);
return response()->json($updatedData);
}

laravel using jQuery Ajax | Ajax Cart

I'm Trying to Save The Product into The Database By Clicking On Add To Cart
But It's Not Adding I Also Use Ajax `
I Want To Add The Cart To DataBase And It's Not Adding.
This is The Error That I cant Add Any Product To The Cart Because Of It
message: "Call to undefined method App\User\Cart::where()", exception: "Error",…
enter image description here
Model Page.
class Cart extends Model
{
use HasFactory; I
protected $table = 'carts';
protected $fillable = [
'user_id',
'prod_id',
'prod_qty',
];
}
Controller page.
public function addToCart(Request $request)
{
$product_qty = $request->input('product_qty');
$product_id = $request->input ('product_id');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->pname." Already Added to cart"]);
}
else
{
$cartItem - new Cart();
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status' => $prod_check->pname." Added to cart"]);
}
}
}
else{
return response()->json(['status' => "Login to Continue"]);
}
}
javascript page.
This Is MY First Time To Use Ajax And Sure That Every Thing Is Correct I Want Know Why Its Not Add
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
success: function (response) {
alert(response.status);
}
});
// alert(product_id);
// alert(product_qty);
// // alert ("test ") ;
});
Route:
Route::middleware(['auth'])->group(function () {
Route::post('/add-to-cart', [App\Http\Controllers\User\indexController::class, 'addToCart' ]);});
So why this error occurs, how can I fix it?`
This look like an error in importation like App\Models\Cart not like this?
verify if you had added use App\Models\Cart;

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

On get request why do I get back the blade view, when I should get data from the database instead?

I a have the following get request, which is executed on mounted().
In some weird mysterious ways, I get back my main view app.blade as a response when I am clearly requesting some data from the database.
Can someone spot what I messed up?
My get request on the front-end:
mounted() {
this.getProjectRequests();
},
methods: {
getProjectRequests: function() {
var self = this;
let clientId = this.$route.path.substring(
this.$route.path.lastIndexOf("/") + 1
);
axios({
method: "get",
url: "/get-project-requests/" + clientId
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
// TODO error handling
});
}
}
My route:
Route::get('/get-project-requests/{client_id}',
'SinglePageController#getProjectRequests');
And my controller method:
public function getProjectRequests($clientId) {
try {
$projectRequests = ProjectRequest::where('client_id',
$clientId)->value('name');
return response()->json( [
'success'=> true,
'projectRequests' => $projectRequests
]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'getting
project requests failed'];
}
}
I think this ProjectRequest::where('client_id', $clientId)->value('name'); giving exception.
Either you check your laravel.log inside storage/logs folder or change that method into
// Not working on eloquent model
$valueOject = ProjectRequest::where('client_id',$clientId)->value('name');
// DB facade its working. Change to this method
$valueOject = DB::table('{your_table}')->where('client_id', $clientId)->value('name');
dd($valueOject);

Resources