Eloquent not removing record from database on AJAX call - ajax

I'm trying to implement a "like" system for posts and there's an animated button by CSS and three AJAX calls through post.
One that will check if the post is already liked and will apply certain style to the button.
One that will add a record to the table in case that an user clicks the button.
One that will delete the record in case the user click it again.
AJAX code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '/like/alreadyLiked',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function (data) {
if(data.display === true){
$('#likelink').attr('class', 'like active')
}else{
$('#likelink').attr('class', 'like');
}
}
});
if($('#likelink').hasClass('like') && $('#likelink')[0].classList.length == 1){
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/like',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}else{
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/dislike',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}
});
PHP (Laravel code):
public function hasHeAlreadyLikedThisPost()
{
if(request()->ajax()){
$post = Post::where('slug', '=', request()->input('slug'))->first();
$post_id = $post->post_id;
$like = Like::where(['user_id' => request()->input('user_id'), 'post_id' => $post_id])->first();
if($like != null){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function addLike()
{
if(request()->ajax()){
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::create(array(
'user_id' => $user_id,
'post_id' => $post->post_id
));
if($like->exists){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function dislike()
{
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->delete();
return response()->json(['display' => false]);
}
The issue is that the "check" and the "insert" calls work but the "delete" one doesn't. In any case it will add a new record to the db and won't change the style.

I think that you have forgot to call first (or get)
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->first()->delete();
where() returns a query,but delete seems to work on eloquent model objects. So to get model object from query so you will call first() (like you did before), or get() to get an array and iterate through it applying delete() on each

Try by putting
$(document).on('click', '#likelink', function(e)
instead of $('#likelink').on('click', function(e)

Related

Update multiple record by id in one controller laravel 8 with ajax

in this case, I want to update data with several records based on selected id.
route :
Route::get('/ikumaster/update-selected-achievmentIKU', [IkumasterController::class, 'updateSelectedAchievmentIKU'])->name('produk.update_selected_achievmentIKU');
ajax :
$(document).on('click', '#bulk_update', function(){
action: function () {
$.ajax({
url:"{{ route('produk.update_selected_achievmentIKU')}}",
method:"get",
data:{id:id}
})
.done(response => {
showAlert(response.message, 'success');
table.ajax.reload();
})
.fail(errors => {
showAlert('Cannot update data!');
return;
});
}
}
controller :
public function updateSelectedAchievmentIKU(Request $request)
{
$nameIku = Ikumaster::where('id', $request->id)->pluck('name')->first();
foreach ($request->id as $id) {
if ($nameIku == '123') {
$ikumaster->achievment = 100;
$ikumaster->update();
} elseif ($nameIku == '456') {
$ikumaster->achievment = 200;
$ikumaster->update();
} else {
}
}
return response()->json(['data' => $ikumaster , 'message' => ' update success ']);
}
The above code only works for update achievements with the same value (100) in all selected records.
Any suggestions so I can update achievements based on the selected id and name?
thanks a lot for the advice

How to return resonse from ajax and display it in Blade file in laravel 8

I am trying to integrate sorting system in laravel application, I am able to do ajax call and got the response but how to display that data in blade file.
I have the data already displayed on search page now if user try to sort the and old data will replaced by the new data.
How can I do that.
Controller Code :
public function sort_data(Request $request){
$results='';
if(request()->sub_sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_sub_category);
})->paginate(24);
} elseif (request()->sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_category);
})->paginate(24);
} elseif (request()->category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->paginate(24);
} else{
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->paginate(24);
}
// $returnHTML = view('pages.user.shop.products.products')->with(["products"=>$results])->render();
// return response()->json(array('success' => true, 'html'=>$returnHTML));
// return response()->json(['products' => $results, 'status' => 200]);
return view('pages.user.shop.products.products')->with(["products"=>$results]);
}
I have already tried the commented code. But not success
$(document).ready(function(){
$('#soting-select').on('change', function(){
var value = document.getElementById('soting-select').value;
var ajaxurl = '/sort-product';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: {
'sorting_selection' : value
},
success: function(response){
console.log(response);
}
});
});
});
Old Response :
New Response :
You can call render() on the view.
And also you may need to change the $results variable to $products as you have shared the data with $products variable in your blade file.
$returnHTML = view('pages.user.shop.products.products', compact('products'))->render();
See the View source code for more information.

Laravel if id exist then update record

i want to set condition, if teacher already exist in database then update record, if id doesn't exist then add record in database. how can i achieve it using ajax in laravel?
Update.js:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("ok");
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("ok");
},
});
});
});
Store.Js:
jQuery(document).ready(function($) {
$("#add-data").submit(function (e) {
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
data.responseJSON;
refreshTable();
},
});
});
});
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
Store Controller:
public function store(Request $request)
{
$teacher = new Teacher;
$teacher=teacher::create($request);
}
There's a custom method for this
$teacher = Teacher::firstOrCreate($id, [
// Pass data here
]);
And if you want to check manually and traverse the request to another method
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if (is_null($teacher)) { // If model not found, pass request to store method
$this->store($request);
}
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
From the docs
Hope this helps
Eloquent provides a updateOrCreate method so you can update or create a record.
$teacher = Teacher::updateOrCreate([
// attributes to search for
'name' => 'Test Teacher',
], [
// values
'grade' => 6,
]);
This would find a teacher with name 'Test Teacher' and update grade to 6 or create a new teacher with name 'Test Teacher' and grade set to 6.
"You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model ..." - Laravel 6.0 Docs - Eloquent - Other Creation Methods - updateOrCreate

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.

How get data from ajax object in controller Laravel?

In ajax I have 3 objects 'emp_info, leave_detail, and leave_items' in controller I don't know how to get record of each object. Could you help me please?
$.ajax({
type: 'POST',
url: '/leave-request-initiator/store',
data: {_token: $('#_token').val(), emp_info: $('#frm_emp_info').serialize(), leave_detail: $('#frm_leave_detail').serialize(), leave_items: leave_items},
beforeSend: function () {
console.log('sending');
},
success: function (response) {
console.log(response);
}
});
Controller.
public function store(Request $request)
{
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
$leaveDetail = new HREmpLeave([
'EMPCODE' => $empcode,
'LEAVECODE' => $request->get('LEAVECODE'),
'FROMDATE' => $request->get('FROMDATE'),
'TODATE' => $request->get('TODATE'),
'BACKTOWORKON' => $request->get('BACKTOWORKON'),
'NODAY' => $request->get('NODAY'),
'REMARK1' => $request->get('REMARK1')
]);
$leaveDetail->save();
}
Change this:
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
to this:
$emp_info = parse_str($request->emp_info); //parse into a array
$empcode = $emp_info['EMPCODE'];

Resources