laravel using jQuery Ajax | Ajax Cart - laravel

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;

Related

how to solve paypal login tab missing when integrate with paypal

I want to do paypal integration in Laravel. I have use composer require srmklive/paypal to install the srmklive/paypal package for my project. I get 404 error when I want to press the PayPal button. The popup paypal login tab will missing. Then I inspect the network I get the error like image given.
Here is my code:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$plan = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "30"
],
"description" => "Item 1"
]
]
]);
return response()->json($plan);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
Here is the code from blade file
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":30
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg);
}
});
}
}).render('#paypal-button-container');
The error show like image given.
Does anyone know how to solve it?
Does the route api/paypal/order/create/ exist on your server? From the error message, it's returning a 404.
The route must exist (no 404) and successfully output a JSON response with an id obtained from the PayPal API.

How to return back to a paginated page?

Using Laraver Inertia Vue
I use a vue with a paginated list of posts. For each post I only load a few column from the database such as title and author. Then I visit url to load the details of a chosen post in the list. I do so using visit url with the lazy loading functionality. After that I am ready to edit the post without reloading the full page. Once the post is updated I submit it and correctly save it into the database. After that I can return back to the page. Everything happens without any reloading on the list.
In order to be able to load the details on a specific post lazily, my on controller is like this.
class PostController extends Controller
{
public function Index($id = null)
{
$this->id = $id;
return Inertia::render('Posts/Index', [
'posts' => Post::select('id', 'title', 'created_at')
->addSelect([
'userfirstname' => User::select('firstname')->whereColumn('id', 'posts.user_id'),
'userlastname' => User::select('familyname')->whereColumn('id', 'posts.user_id')
])
->orderBy('created_at', 'DESC')
->paginate(10),
//lazily evaluated
'details' => function () {
if ($this->id) {
$post = Post::find($this->id);
} else {
$post = null;
}
return $post;
},
]);
}
public function Update(Request $request)
{
$request->validate([
'id'=>'required',
'abstract'=>'required',
//TODO :to be completed
]);
$post=Post::find($request->input('id'));
$post->abstract=$request->input('abstract');
$post->title=$request->input('title');
//TODO to be completed
$post->save();
return Redirect::back();
}
}
and the method I use to load page and details are these:
//visit this url to get the lazzy evaluation of post details
if (to_visit) {
this.$inertia
.visit(`/posts/${to_visit}`, {
method: "get",
data: {},
replace: false,
preserveState: true,
preserveScroll: true,
only: ["details"],
headers: {}
})
.then(to_visit => {
console.log("fetched " + this.details.title);
});
}
},
updatePost(form) {
console.log("form submitted");
this.$inertia.visit(`/post`, {
method: "put",
data: form,
replace: false,
preserveState: true,
preserveScroll: true,
only: [],
headers: {}
});
},
This works fine as long as the particular post I update is on the first page, but when it is on the any other paginated page on the list, post saving is ok but I don't return on the paginated page but always on the first one.
Would be happy to ear about a solution!

Render Laravel Component via Ajax method

How can i render component that is sent from controller via an ajax request? For example i want to dynamically filter product using this method:
Load the index URL
Fetch the products based on the filter category or return all the products using ajax
My ajax Code:
$(document).ready(function () {
filterData();
// Filter data function
function filterData() {
// Initializing loader
$('#product-listing-row').html('<div id="loading" style="" ></div>');
var action = 'fetchData';
var subCategory = getFilter('sub-category');
/* LARAVEL META CSRF REQUIREMENT */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Ajax Call
$.ajax({
url: "/shop/filter",
method: "POST",
data: {action: action, subCategory: subCategory},
success: function (data) {
$('#product-listing-row').html(data);
}
});
}
// Get Filter by class name function
function getFilter(className) {
var filter = [];
$('.' + className + ':checked').each(function () {
filter.push($(this).val());
});
//console.log(filter);
return filter;
}
$('.common-selector').click(function () {
filterData();
});
});
I am getting all the filters from ProductController
Instead of manually writing html in controller I want to return the specific component from the controller
ProductController:
public function productFilter() {
if (!request()->action) abort('500');
// Starting the query for products which are active
$products = Product::where('is_active', '1');
//dump(request()->subCategory);
/* Checking the filters */
// sub category exists
if (request()->subCategory) $products = $products->where('sub_category_id', request()->subCategory);
// Completing the query
$products = $products->orderBy('created_at', 'DESC')->paginate(15);
// Adding reviews and total review
$products = Product::setProductReviewTotalReviewsAttr($products);
foreach ($products as $product)
//view('components.shop-product', ['product' => $product])->render();
echo '<x-shop-product :product="$product"></x-shop-product>';
}
Instead of getting the components rendered, I am receiving the whole string echoed out. Is there any way i can just get the components rendered?
Thanks in advance
Actually now I found a way to do it myself
I applied the following to the ProductController
return View::make("components.shop-product")
->with("product", $product)
->render();
Updated Code:
public function productFilter() {
if (!request()->action) abort('500');
// Starting the query for products which are active
$products = Product::where('is_active', '1');
//dump(request()->subCategory);
/* Checking the filters */
// sub category exists
if (request()->subCategory) $products = $products->where('sub_category_id', request()->subCategory);
// Completing the query
$products = $products->orderBy('created_at', 'DESC')->paginate(15);
// Adding reviews and total review
$products = Product::setProductReviewTotalReviewsAttr($products);
$output = '';
foreach ($products as $product) {
$output .= View::make("components.shop-product")
->with("product", $product)
->render();
}
if (count($products) > 0)
echo $output;
else
echo '<div class="col">No Data</div>';
}
with laravel > 8 you can use \Blade::render directly in your controller to render even anonymouse components, here I'm rendering a table component with a lot of properties:
class componentController extends Controller {
public function index(){
$table = [
:tableid => "table"
:thead => ["id","name","job"]
:data => [
["1","marcoh","captain"],
["2","sanji","cook"]
],
tfoot => false
];
// Renders component table.blade.php
return \Blade::render('
<x-table
:tableid="$tableid"
:thead="$thead"
:data="$data"
tfoot
/>
', $table);
...

The Ajax pagination to my account not run

I would like to create an Ajax pagination of my articles in my account, here is my code that I created but it does not work I do not know how to do.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
I would like to have the javascript code
$(document).ready(function () {
$(document).on('click','.pagination a',function(e){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$.ajax({
url: url,
method: 'GET',
data: {},
dataType: 'json',
success: function (result) {
if (result.status == 'ok'){
$('#userListingGrid').html(result.listing);
}else{
alert("Error when get pagination");
}
}
});
return false;
})
});
I would have a check on your controller for an ajax request like so:
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
if(request()->ajax()){
return response()->json(['user' => $user, 'articles' => $user->articles()->orderByDesc('created_at')->paginate(4);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
Then you don't have to load your view every time and you can let your javascript functions take care of the DOM manipulating of the results. Not sure if that's what you are looking for. I know that you would probably need a {{$articles->links()}} at the end of your view to go through each page.

User creation does not work on laravel 5.1

actually i try to migrate some users from a excel file (.xlsx) to login in my aplication. But the code doesn't work.
The strange part is that the same code it's implemented for migrate payroll from a excel file (.xlsx) and this one work. I try many options, change some code, but it doesn't work.
Maybe I'm letting some error out and someone else can see it. I would appreciate the help.
Edit: I have a code in my routes.php that performs the migration, but from a table in the database, and this one works
My routes.php
Route::get("user_mig", function()
{
$contr = temporalestla\ContractUser::all();
foreach ($contr as $value)
{
$psw = \Hash::make($value->id_employee);
$user = new temporalestla\User
([
"full_name"=>$value->name_used,
"user" => $value->id_employee,
"password" => $psw,
"perfil" => 1
]);
$user->save();
}
return "Proceso finalizado";
});
My ImportController.php from users
public function cargar_datos_users(Request $request)
{
$file= $request->file('file');
$original_name=$file->getClientOriginalName();
$r1=Storage::disk('files')->put($original_name, \File::get($file) );
$route= storage_path('files') ."/". $original_name;
if($r1)
{
Excel::selectSheetsByIndex(0)->load($route, function($sheet)
{
$sheet->each(function($row)
{
$user = new User;
$user->full_name = $row->nombreempleado;
$user->user = $row->empleado;
$user->password = bcrypt($row->empleado);
$perfil = 1;
$user->perfil = $perfil;
$user->save();
});
});
return view("administrator.contracts.adminpayrolls")->with("msj","Usuarios Cargados Correctamente");
}
else
{
return view("administrator.contracts.adminpayrolls")->with("msj","Error al subir el archivo");
}
}
My app/User.php
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['full_name', 'user', 'password','perfil'];
protected $hidden = ['password', 'remember_token'];
}
The ajax script located in view.blade.php
<script type="text/javascript">
$(document).on("submit",".formarchivo",function(e)
{
e.preventDefault();
var formu=$(this);
var nombreform=$(this).attr("id");
if(nombreform=="f_cargar_datos_users" ){ var miurl="cargar_datos_users"; var divresul="notificacion_resul_fcdu"}
var formData = new FormData($("#"+nombreform+"")[0]);
$.ajax
({
url: miurl,
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function()
{
$("#"+divresul+"").html($("#cargador_empresa").html());
},
success: function(data)
{
alert("Usuarios cargados correctamente");
location.reload(true);
},
error: function(data)
{
alert("Error al subir usuarios. intente nuevamente");
location.reload(true);
}
});
});
</script>
#endsection
The plugin for migrate from excel is http://www.maatwebsite.nl/laravel-excel/docs
As I said, the same structure work on payroll migrate, but don't work on users migrate, any comments will be appreciate.

Resources