how insert data json into database laravel? - ajax

I use ajax to get data json and send it to my controller, now I want to insert this data into table pointages help me please wher is the error. here is ajax code:
he give me this error
$('.add-all').on('click', function() {
var items = [];
let valu = $('#datePicker').val();
$("tr").each(function(i,r){
if ( i > 0 && $(r).find("input").first().prop("checked"))
{
items.push({"matricule": r.cells[3].innerText, "salaire": r.cells[5].innerText, "date" : valu })
}
});
//ajax
$.ajax({
method : 'POST',
url : 'mois',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data : {"items":items}, // pass in json format
success : function(data) {
console.log(data);
},
error : function(err){
console.log(err)
}
});
//fin ajax
});
Controller:
public function addMultiple(Request $request){
foreach($request->get('items') as $item){
$pointage = Pointage::create([
'matricule' => $item->$item['matricule'],
'datep' => $item->$item['datep'],
'solde' => $item->$item['salaire']
]);
}
return redirect("mois");
}
modele Pointage :
class Pointage extends Model
{
/**
*
*
* #var array
*/
protected $fillable = [
'matricule', 'datep', 'solde',
];
}
table pointages:the other fields is nullable
public function up()
{
Schema::create('pointages', function (Blueprint $table) {
$table->increments('id');
$table->integer('matricule');
$table->date('datep');
$table->double('nbrj');
$table->double('prime');
$table->double('solde');
$table->timestamps();
});
}

what do you have in the line 79? I think could be
'matricule' => $item['matricule'],
instead
'matricule' => $item->$item['matricule'],

Related

Ajax to call Symfony controller

I'm trying to call a method with ajax.
ajax connection is succeed and no error message was appeared.
the JS code
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{url('change_order_status')}}",
data: id,
async: false,
})
.done(function() {
console.log('success');
})
.fail(function () {
console.log('error');
});
});
but the method in the controller seemingly not working.
controller
/**
* #Method("POST")
* #Route("/%eccube_admin_route%/", name="change_order_status")
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
dump($rquest);
}
I don't know what is wrong with it.
Please help.
I insert the js to every pages as an snippet is that's why it doesn't work properly.
You must return an instance of Response class in a controller . So here, what you can do is to return a JsonResponse
return new JsonResponse($request->getContent());
May be you can try this.
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{ path('change_order_status') }}",
data: {
id : id
},
async: false,
})
.done(function(data) {
console.log(data)
console.log('success');
})
.fail(function () {
console.log('error');
});
});
/**
* #Route("/%eccube_admin_route%/", name="change_order_status", methods={"POST"})
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
$id = $request->request->get('id');
// Try to dump your request
// dd($request);
return $this->json([
'success' => true
]);
}
I just don't know what eccube_admin_route mean.
And don't forget to extend AbstractController in your controller class
This is example from my project. Try to dump your controller object and use symfony debugbar to open your ajax request, click on url columns

Subscriptions and subscription_item database is empty using Stripe checkout

I try to create a website using Stripe for monthly subscription.
I got a pricing page, when i choose a product, i create a checkout session using JS, and when i pay, i got successfully the payement and everything, but my subscription database is empty. The default cashier webhook do nothing but he are called successfully on my stripe cli, I also tryied to create a webhook but i got nothing from it i got every times error 500 on stripe cli.
Do you have an idea ?
Here is my JS
<script src="https://js.stripe.com/v3/"></script>
<script defer>
$("#form").submit(function(e){
e.preventDefault();
});
var handleResult = function(result) {
if (result.error) {
showErrorMessage(result.error.message);
}
};
function subscribe(offer)
{
fetch("{{ route('subscription_setup') }}", {
method: "GET",
headers: {
"Content-Type": "application/json",
}
})
.then((result) => result.json())
.then(function(result) {
var publishableKey = result.publishableKey;
var stripe = Stripe(publishableKey);
var createCheckoutSession = function(offer) {
return fetch("{{ route('subscription_create_checkout_session') }}", {
method: "POST",
headers: {
"Content-Type": "application/json",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
body: JSON.stringify({
offer: offer
})
}).then(function(result) {
return result.json();
});
}
createCheckoutSession(offer).then(function(data) {
stripe.redirectToCheckout({
sessionId: data.sessionId
}).then(handleResult);
});
})
}
</script>
Here is my PHP :
<?php
namespace App\Http\Controllers;
use Exception;
use Illuminate\Http\Request;
use \Stripe\Stripe;
use Illuminate\Support\Facades\Auth;
use Laravel\Cashier\Cashier;
use \Stripe\Checkout\Session;
class SubscriptionController extends Controller
{
public function __construct() {
Stripe::setApiKey(env('STRIPE_SECRET'));
}
public function index()
{
return view('subscription/index');
}
public function create_checkout_session(Request $request)
{
$user = Auth::user();
// User is not in stripe database
if(empty($user->stripe_id))
{
$stripe_user = $user->createAsStripeCustomer();
}
// User already in stripe database
else
{
$stripe_user = Cashier::findBillable($user->stripe_id);
}
// After retrieve the stripe user
$offer = $request->post('offer');
if($offer == 'football')
{
$price = 'price_1I4z8kDdfEiamf5bMiTElVAM';
}
else
{
return response()->json(['error' => 'Vous n\'avez pas sélectionné une offre valide']);
}
$checkout_session = Session::create([
'payment_method_types' => ['card'],
'line_items' => [
[
'price' => $price,
'quantity' => 1,
],
],
'mode' => 'subscription',
'success_url' => url('/'),
'cancel_url' => url('/subscription'),
'customer' => $stripe_user['stripe_id']
]);
return response()->json(['sessionId' => $checkout_session['id']]);
}
public function setup()
{
return response()->json([
'publishableKey' => env('STRIPE_KEY')
]);
}
}
I'm open to every suggestions, thank's a lot.
Edit :
My custom webhook
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;
use \Stripe\Subscription;
use Illuminate\Support\Facades\DB;
class WebhookController extends CashierController
{
/**
* Handle invoice payment succeeded.
*
* #param array $payload
* #return \Symfony\Component\HttpFoundation\Response
*/
public function handleInvoicePaymentSucceeded($payload)
{
$session = $payload['data']['object'];
$user = Auth::user();
// $plan = Subscription::retrieve($session['subscription']['items']['data']['price']['id']);
DB::transaction(function () use ($session, $user) {
$user->update(['stripe_id' => $session['customer']]);
$user->subscriptions()->create([
'name' => 'default',
'stripe_id' => $session['subscription'],
'stripe_status' => 'active',
'stripe_plan' => 'price_1I4z8kDdfEiamf5bMiTElVAM',
'quantity' => 1,
'trial_ends_at' => null,
'ends_at' => now()->addDays(30),
]);
});
return $this->successMethod();
}
}
My verifycsrftoken.php
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'stripe/*',
];
}
my routes :
Route::post('/stripe/webhook', [WebhookController::class, 'handleWebhook']);
I got a error 500 into my stripe cli while i sub to a product.
Edit : I finally used this tutorial https://weeklyhow.com/create-website-subscription-with-laravel-cashier/#:~:text=Laravel%20cashier%20is%20a%20package,and%20even%20generate%20invoice%20PDFs. and don't use stripe checkout anymore.

How to insert data json in database laravel?

I use a jquery and ajax to get data json and send it to my controller, now I want to insert this data into table pointages help me please.
here is jquery ajax code:
$('.add-all').on('click', function() {
var items = [];
let valu = $('#datePicker').val();
$("tr").each(function(i,r){
if ( i > 0 && $(r).find("input").first().prop("checked"))
{
items.push({"matricule": r.cells[3].innerText, "salaire": r.cells[5].innerText, "date" : valu })
}
});
//ajax
$.ajax({
method : 'POST',
url : 'mois',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data : {"items":items}, // pass in json format
success : function(data) {
console.log(data);
},
error : function(err){
console.log(err)
}
});
//fin ajax
});
Controller :
public function addMultiple(Request $request){
$data = $request->only('datep','salaire','matricule');
$pointage['data'] = json_encode($data);
Pointage::insert($pointage);
}
i get :
data: {…}
items: (3) […]
0: Object { matricule: "1", salaire: "6000", date: "2019-06-23"}
1: Object { matricule: "2", salaire: "5000", date: "2019-06-23"}
2: Object { matricule: "3", salaire: "7000", date: "2019-06-23" }
length: 3
<prototype>: Array [
<prototype>: {…
model Pointage:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pointage extends Model
{
//
}
table pointages
public function up()
{
Schema::create('pointages', function (Blueprint $table) {
$table->increments('id');
$table->integer('matricule');
$table->date('datep');
$table->double('nbrj');
$table->double('prime');
$table->double('solde');
$table->timestamps();
});
}

How to Store Array Value From Select2 JS in Laravel

I'm using MySQL Database. I have select2 js with multiple value
Here is my code
My Blade View And JS
<input type="text" class="form-control tools_id" name="tools_id[]" multiple/>
var $tools_id = jQuery('.tools_id');
$tools_id.select2({
multiple: true,
placeholder: 'Tools',
ajax: {
url: 'sample/gettools',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
q: term, //search term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tools,
id: item.tools_id
}
})
};
},
cache: true
}
});
My Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sample extends Model
{
protected $primaryKey = 'id';
public $incrementing = false;
protected $table = 'lab_sample';
protected $casts = [
'tools_id' => 'array'
];
protected $fillable = ['name','summary','tools_id'];
}
My Controller
public function store(Request $request)
{
$sample = Sample::create([
'name' => $request->name,
'summary' => $request->summary,
'tools_id' => $request->input('tools_id'),
]);
return Response::json($sample);
}
My code was successfully save the data, but the problem is when i selected more than one value/tags, it saved the array value (tools_id) like this
["20,21"]
Where it supposed to be like this
["20","21"]

Laravel / AJAX Like Button Error: Request failed with status code 404

I'm very new to Laravel, AJAX etc. I am a student working on a Twitter type project and this is my first stack question ever made. I've tried to look for answers but the code that my teacher has helped me with is very different from other examples. I'm pretty sure that my problem is with the unlike method inside of my "Tweet Controller"... Any help is greatly appreciated! Hopefully I have provided enough information and hopefully this can help others in the future :)
This is my error:[1]: https://i.stack.imgur.com/zkxsd.png
POST http://localhost:8000/tweets/19/unlike 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:14253)
at settle (app.js:35706)
at XMLHttpRequest.handleLoad (app.js:14127)
This is my likes table / migration
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('tweet_id');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}
This is my Tweet Controller
public function like($id){
$like = Like::create([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return json_encode(array('status' => 'success'));
}
return json_encode(array('status' => 'failed'));
}
public function unlike($id){
$like = Like::delete([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return json_encode(array('status' => 'success'));
}
}
This is my Web Routes
Route::post('tweets/{tweet}/like', 'TweetController#like');
Route::delete('tweets/{tweet}/like', 'TweetController#unlike');
This is my Model
public function likes(){
return $this->hasMany(Like::class);
}
public function likedByCurrentUser(){
$userId=auth()->id();
//like boolean
$like = $this->likes->first(function($v) use ($userId){
//$v is a reference to the single like
return $v->user_id == $userId;
});
//if the user has liked a post
if($like){
return true;
}
return false;
}
This is my Vue Component:
<script>
export default {
name: 'likeButton',
props: ['likeCount','hasLiked','tweetId','csrf'],
mounted(){
this.dataLikeCount = this.likeCount;
this.dataHasLiked = this.hasLiked;
},
data(){
return{
dataLikeCount:0,
dataHasLiked:false
}
},
methods:{
doLike(){
var type='like';
if(this.dataHasLiked){
type='unlike'
}
axios({
method:'POST',
url:'/tweets/' + this.tweetId + '/'+ type,
headers:{
'X-CSRFToken':this.csrf
},
json: true
}).then((response) => {
if(response.data.status == 'success'){
// response was successful (regardless of type)
return true
// if type is like
// add one to like count, set hasLiked to true
if(type == 'like'){
this.dataLikeCount++
}
// if type is unlike
// deduct one from like count, set hasLiked to false
if(type =='unlike'){
return false
this.dataLikeCount--
}
}
});
}
}
}
</script>
<template>
<div>
<button type="submit"
:class="{'btn btn-link':dataHasLiked}"
#click="doLike">
<i class="star"></i>
Like {{ dataLikeCount }}
</button>
</div>
</template>
You dont have a matching route for unlike.
Change
Route::delete('tweets/{tweet}/like', 'TweetController#unlike');
To
Route::delete('tweets/{tweet}/unlike', 'TweetController#unlike');
Use this
Route::delete('tweets/{tweet}/unlike', 'TweetController#unlike');
As said by #DigitalDrifter you doesn't have route for unlike. so need to change that.
Your routes is like
Route::delete('tweets/{tweet}/unlike', 'TweetController#unlike');
So have to call this route with DELETE method using ajax. you have ajax call with post method.it will also give method not allowed error.
So change your web route,
From
Route::delete('tweets/{tweet}/unlike', 'TweetController#unlike');
To
Route::post('tweets/{tweet}/unlike', 'TweetController#unlike');
And change return response in your controller methods, It will look like below
Tweet Controller
public function like($id){
$like = Like::create([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return response()->json(['status' => 'success']);
}
return response()->json(['status' => 'failed']);
}
public function unlike($id){
$like = Like::delete([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return response()->json(['status' => 'success']);
}
}
Hope it helps now!!

Resources