Laravel how to pass data from controller to modal dialogue using ajax - php

I have items and for every item there are related items, so when I open the homepage it shows all item, when I want to click on any item, ajax will pass this item id to controller to get the related items for this item, the problem is I want to show the related item in a modal dialogue, the modal dialogue now show all related items to all items not to the current item.
I think the problem is because the include of modal in the homepage which has the foreach!, hope you can help me in solving this issue
route
Route::get('/',['as'=>'showItems','uses'=>'HomeController#getItem']);
Route::get('Get_relateditem',['as'=>'Get_relateditem','uses'=>'HomeController#getItem']);
ajax
$(function(){
$('.Item_root').on("click", function () {
var item_id = $(this).data('id');
$.ajax({
type:'get',
url: '/',
data: {
'_token': $('input[name=_token]').val(),
'item_id':item_id,
},
success:function(data){}
});
});
});
controller
public function getItem(Request $request)
{
$currentitemid =$request->item_id;
$ritems = Relateditem::orderBy('id', 'asc')->where('ritemf_id','LIKE','%'.$currentitemid.'%')->with('items')->get()->groupBy('ritemf_id');
$items = Item::orderBy('category_id', 'asc')->with('category')->get()->groupBy('category_id');
$categories = Category::orderBy('category_id', 'asc')->get();
return view('home')->with('items',$items)->with('categories',$categories)->with('ritems',$ritems);
}
}
modal
#foreach($ritems as $item_id => $realtedItems)
#foreach($realtedItems as $ritem)
<div class="SuggestedItem_container">
<label color="red" class="Checker_root Checker_red Checker_left">
<input type="checkbox" class="Checker_input" value="on">
<div class="SuggestedItem_nameContainer">
<div>
<span class="SuggestedItem_name">{{$ritem->riteml_id}}</span>
<span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$3.95</span></div></div>
<div class="SuggestedItem_description styles_small styles_base styles_spacing-base">
<span class="SuggestedItem_category styles_bold">Appetizers</span>
<span> · Edamame soybean pods harvested right before the beans begin to harden are lightly boiled and seasoned with sea salt.</span>
</div>
</label>
</div>
#endforeach
#endforeach

Modify routes:
Route::get('/','HomeController#getItem');
Route::get('/get_related_items/{id}','HomeController#getRelatedItems');
modify getItem to get only the items and categories:
public function getItem(Request $request)
{
$items = Item::orderBy('category_id', 'asc')
->with('category')->get()
->groupBy('category_id');
$categories = Category::orderBy('category_id', 'asc')->get();
return view('home',['items' => $items,'categories' => $categories]);
}
get related items for a single item id:
public function getRelatedItems(Request $request, $id)
{
$ritems = Relateditem::orderBy('id', 'asc')
->where('ritemf_id',$id)
->with('items')
->get()
->groupBy('ritemf_id');
return response()->json($ritems);
}
now for the js part:
$(function(){
$('.Item_root').on("click", function () {
var item_id = $(this).data('id');
$.ajax({
type:'get',
url: '/get_related_items/' + item_id,
data: {
'_token': $('input[name=_token]').val()
},
success:function(data){
if(data && data.length){
var con_el = $('.SuggestedItem_container');
for(var i = 0; i < data.length;i++){
var related_item_el = "<div class='related_item'><p>" + data[i].id + "</p></div>"
con_el.append(related_item_el);
}
}else{
console.log('no related items found');
}
}
});
});
});
this will insert all the related items inside the SuggestedItem_container
i didn't write the view template cuz that part is easy, and note that i only included the related item id as example cuz i don't know what fields the item has.
i hope this helps you

Related

How to send dropdown selected value through ajax call to controller in laravel

I'm new with laravel and I want to send the selected dropdown option value of product name through ajax data to the controller
For Example: If I'm select 1st plastic product option value from a drop-down then in the controller from request object I want that selected product name
as per my below code I'm getting null in the request object of the product name
Here is my route:
Route::get('product', 'ProductController#index')->name('product');
Here is my controller:
public function index(Request $request)
{
if (isset($request->productName)) {
$productName = $request->productName;
dump($productName); // getting null
} else {
$productName = null;
}
return view('Product.product');
}
Here is my an ajax call:
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('product')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e,'error');
}
});
}
header request result
I don't know if I'm doing something wrong,
ends with wanting to get help from helping hands please help me to get the selected value to the controller object
I believe you got null because you are returning a full HTML to the Ajax request. In order to get the payload sent from the Ajax, you have to return a JSON response like this:
public function index(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
That being said, I'm unable to reproduce the issue without seeing how do you call the method and where would you show the data to. And I assume you want to simply just do a console.log(data) like you did on the given snippet. In this case, the snippet above will work.
And if you want to keep the view to prevent error when you refresh the page, just add a new method for that specific call in your controller and send the request to that endpoint, like this:
web.php
<?php
Route::get('/', [ProductController::class, 'index']);
Route::get('/productFilter', [ProductController::class, 'productFilter'])->name('dashboard-product-data');
ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
return view('welcome');
}
public function productFilter(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
}
welcome.blade.php
<div>Product Name: <span id="product-name"></span></div>
<select id="product_filter" name="product_filter">
<option value="plastic product">plastic product</option>
</select>
<button id="submit-button" type="button">Send data</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('dashboard-product-data')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
document.querySelector('#product-name').innerHTML = data
},
error:function(e){
console.log(e,'error');
}
});
}
const submitButton = document.querySelector('#submit-button')
submitButton.addEventListener('click', () => display())
</script>

select2 drop-down plugin with auto-populate together with add new record

I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.

laravel5.2 convert laravel code to ajax

I developed this shape with laravel code
When I click on + the quantity of this product increase by 1.
When I click - the quantity of this product decrease by 1.
cart.blade.php (view):
<div class="cart_quantity_button">
<a class="cart_quantity_up" href='{{url("cart?product_id=$item->id&increment=1")}}'> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href='{{url("cart?product_id=$item->id&decrease=1")}}'> - </a>
</div>
Cart function in controller:
public function cart()
{
if (Request::isMethod('POST')) {
$product_id = Request::get('product_id');
$product = Product::find($product_id);
Cart::add(array('id' => $product_id,'name' => $product->name, 'qty' => 1, 'price' => $product->price,'options'=>array('image'=>$product->image)));
}
$id = Request::get('product_id');
//increment the quantity
if ($id && (Request::get('increment')) == 1) {
$p = Request::get('increment');
$rowId = Cart::search(array('id' => $id));
// echo "row id".$rowId."and the p=".$p;
$item = Cart::get($rowId[0]);
// echo "row id".$rowId;
$add = $item->qty + 1;
Cart::update($rowId[0], $add);
}
//decrease the quantity
if ($id && (Request::get('decrease')) == 1) {
$rowId = Cart::search(array('id' => $id));
$item = Cart::get($rowId[0]);
$sub = $item->qty - 1;
echo "item" . $sub;
Cart::update($rowId[0], $sub);
}
if ($id && (Request::get('remove')) == 1) {
$rowId = Cart::search(array('id' => $id));
Cart::remove($rowId[0]);
}
$cart = Cart::content();
return view('cart', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
public function cart_remove()
{
Cart::destroy();
return Redirect::away('cart');
}
public function checkout()
{
$cart = Cart::content();
return view('checkout', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
I want to convert this with ajax code, I do simple code for this
<script>
function getMessage($id)
{
$.ajax({
type: 'POST',
url: 'getmsg',
dataType: 'json',
data: {
valu_id: $id
},
success: function(data) {
$("#msg").html(data.msg);
}
});
}
</script>
<?php
$item_id = 3;
echo Form::button('+',['onClick'=>'getMessage($item_id)']);
?>
<div id='msg'>
<input id="msg" type="text" name="quantity" autocomplete="off" size="2">
</div>
Controller function:
public function ajax()
{
$value= $_POST['valu_id']+1;
return response()->json(array('msg'=>$value), 200);
}
I don't know how to complete this code .I have many question about this code.
like
How to get the product id from cart.blade.php view and put it in getmessage() to use it in ajax function?
How to put getmessage() in <div class="cart_quantity_button"> instead of button onclick to respect of the shape above?
How to return the quantity in the input field as the shape above?
Note: This answer doesn't simply giving you a working solution but an idea on how to handle ajax request/response.
Firstly, even tough event.preventDefault() would prevent default action which is following the URL, I'd rather store the URL to data- attribute.
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&increment=1')}}"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&decrease=1')}}"> - </a>
</div>
How to get the product id from cart.blade.php view and put it in getmessage() to use it in ajax function?
It's always better to listen to an event, which is click in this case.
$('.cart_quantity_up').on('click', function(e) {
//an ajax call here
});
Same code applies for the other one
$('.cart_quantity_down').on('click', function(e) {
//an ajax call here
});
Now, two click events has been attached to each corresponding element. Then, it's time to wrap the ajax function up.
function updateQty(url){
var $qty = $('.cart_quantity_input');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
cart_qty: $qty.val()
},
success:function(data){
$qty.val(data.qty);
}
});
}
The function above is simply
takes a parameter which is URL for ajax to call to,
does a post request with uri param key 'cart_qty'
returns response which is a value of 'qty' from controller to cart_quantity_input input element
And then, put the ajax function to the first snippets (click event)
$('.cart_quantity_up').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
$('.cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
Actually to make things simpler, you can attach the event from multiple selectors at one go.
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route for the 'up'
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
Now, you get the idea on how to create ajax post and retrieve its response to attach it to the input element afterward.
At this point, I'm going to refactor your code. And oh, all of your questions should have been answered at this stage.
Your controller looks a bit messy as you handle both post and get requests for such simple situation. I would rather do just post. Instead of having bunch of conditions, I'll put the footprint inside the data- attribute (again). In the end, I wrap them inside a form, because CSRF token gives more security on your end.
<form name="cart_form">
{{ csrf_field() }}
<input type="hidden" class="item_id" value="{{ $item->id }}">
<div class="cart_quantity_button">
<button type="button" class="cart_quantity_up" data-route="{{url('cart')}}" data-increase="1"> + </button>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<button class="cart_quantity_down" data-route="{{url('cart')}}" data-increase="0"> - </button>
</div>
</form>
You're free to design your own view as long as you're going to do a post request (as I'm doing on it). I'll explain a bit above the logic I'm going to make.
Hold the $item->id on hidden field
Going to make ajax request to url('cart') route and store it to data-route
Add data-increase to differentiate each request should increase or decrease
Now listen up on click event
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var $this = $(this),
url = $this.data('route'),
increase = $this.data('increase');
updateQty(url, increase);
});
Below updateQty function is a bit different from the first one I made. It accepts the second parameter increase as (pseudo-)boolean value. Also notice I'm posting the token as request header rather than body.
function updateQty(url, increase){
var $qty = $('.cart_quantity_input'),
itemId = $('.item_id').val();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
headers: {
'X-CSRF-Token' : $('input[name="_token"]').val()
},
data: {
'cart_qty': $qty.val(),
'item_id': itemId,
'increase': increase
},
success:function(data){
$qty.val(data.qty);
}
});
}
Your controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cart;
use App\Http\Requests;
class YourController extends Controller
{
public function cart(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
$cart = Cart::search(['id' => $id]);
//Note: This code may not working as what you expect
// but it should give you the idea that laravel
// actually has increment and decrement methods
// and else.
if ($request->increase) {
$cart->increment('qty');
} else {
$cart->decrement('qty');
}
$qty = $cart->first(['qty']);
return response()->json(['qty' => $qty]);
}
//rest is your code
//...
}
}
In the above code, I'm trying to
treat ajax request separately from your code,
update qty column based on $_POST['increase']
If 1, do increment. If 0, decrements it
grab the value of qty column (though Im not sure it's going to work)
return the value keyed 'qty' as json
it will then update your input element based on $qty.val(data.qty)

After selecting value from autocomplete suggestions, fill in the rest of the fields based on the selected value

So i have a autocomplete in one of my views, that is working, now i want to add a feature where users searches for product writtes in some key words finds it and selects it, when the name of the product is selected i want to dynamically fill in price for that product, the info is in the database, how can I achieve this?
My JQuery for autocomplete
$(function(){
var controller_path = document.getElementById("get_controller_path").value;
$("#product").autocomplete({
source: controller_path
});
});
My view where i want dynamically the price to popup when autocomplete suggestion is selected:
<td><input type="text" id="product" name="prodname"></td>
<input type="hidden" id="get_controller_path" value="<?echo base_url().'admin_site_offers_ctrl/get_product';?>">
<td><input style="width: 60px" type="text" name="price" id="price"></td>
Controller for autocomplete
public function get_product(){
$this->load->model('offers_for_clients_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->offers_for_clients_model->get_product($q);
}
}
Model for that autocomplete functionality:
function get_product($q){
$this->db->select('*');
$this->db->like('nosauk_lv', $q);
$query = $this->db->get('produkti');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlspecialchars_decode(stripslashes($row['nosauk_lv'])); //build an array
}
echo json_encode($row_set); //format the array into json data
}
}
How should i approach this? Any pointers to right direction would be amazing! Thanks!
P.S The autocomplete is wokring no worries about that.
You can try like this
$("#product").autocomplete({
source: function( request, response ) {
$.ajax({
url: customurl,
data: {term: request.term},
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
// you can set the label value
return {
label: item.value,
value: item.value,
}
}
}));
}
});
},
select: function( event, ui )
{
// Here again you can call ajax function to get the product price
var prodname=$('#prodname').val(ui.prodid);
getproductprice(prodname);
},
change: function( event, ui )
{
var prodname=$('#prodname').val(ui.prodid);
getproductprice(prodname);
}
});
Please make sure in your model get the id of product also in $row_set[].
In html declare like this
<input type="hidden" name="prodname" id="prodname"> // Here you will get product name id after select the productname
In getproductprice function you can call the ajax function to get the price
function getproductprice(prodname)
{
if(prodname>0)
{
$.ajax({
url:customurl,
data: "prodid="+prodname,
dataType: "json",
success: function( data ) {
$('#price').val(data['price']); // whatever your varaible
}
});
}
}
I think this will help to solve your problem. Thanks
Sorry for late reply this worked for me ended up doing this:
$(function(){
var controller_path = document.getElementById("get_controller_path").value;
$("#product").autocomplete({
source: controller_path, // ceļš uz kontrolieri kur atrodas metode, admin_site_offers_ctrl
select: function(a,b){
$(this).val(b.item.value); //grabed the selected value
getProductsOtherInfo(b.item.value);//passed that selected value
}
});
});
Other function made request to database based on the selected values name
and loaded them in the appropriate fields that i needed, like this:
function getProductsOtherInfo(name){
var site_url = document.getElementById('get_products_other_info').value;
/*alert(site_url);*/
$.post(site_url, {
name : name,
site_url : site_url
},
function(rawdata){
var myObject = JSON.parse(rawdata);
$('#cena_pirms_atl').val(myObject[0].cena_ls);
$('#iepcena').html(myObject[0].ped_ien_ls);
$('#nom_id').val(myObject[0].ID);
getPZtotals();
});
}
The controller:
function get_products_other_info(){
$this->load->model('offers_for_clients_model');
$name = trim($_POST['name']);
$data['products_other_info'] = $this->offers_for_clients_model->get_products_other_info($name);
echo json_encode($data['products_other_info']);
}
The model:
function get_products_other_info($name){
$decode_name = htmlspecialchars(stripslashes($name));
$query = $this->db->where('nosauk_lv', $decode_name)->get('produkti')->result();
return $query;
}
View:
<input type="hidden" name="nom_id" id="nom_id">
<td><input style="width: 60px" type="text" name="cena_pirms_atl" id="cena_pirms_atl"></td>
<td id="iepirkcens"><span id="iepcena"></span></td>

Laravel 5 AJAX Sort Order data (jQuery Sortable) with no HTML form

I'm to trying to store a sort order to each article within a help centre for my new site using Laravel 5 and having a bit of trouble getting it to work. I'm using jQuery UI's .sortable for arranging the elements on the page, and since there are going to be multiple sections throughout the site where areas are sortable, my jQuery script is built in a way for a 'one script for all' purposes. Hence the use of data-* attributes and route name references.
Here is the code I've got so far:
routes.php
Route::post('admin/help-centre/category/{category_id}/section/{section_id}/article/sort-order', 'AdminHelpCentreArticleController#sortOrder');
AdminHelpCentreArticleController.php
public function sortOrder($category_id, $section_id)
{
/* Return ------------------------------------- */
return [
'category_id' => $category_id,
'section_id' => $section_id
];
}
show.blade.php (Admin Article Listing)
<ul id="help-center-articles-sort" class="sortable">
#foreach ($helpCentreArticles as $helpCentreArticle)
<li class="sortable-element" data-sortable-element-id="{{ $helpCentreArticle->id }}">
{{ $helpCentreArticle->title }}
</li>
#endforeach
</ul>
Save Order
scripts.js (includes CSRF Token _token)
var csrfToken = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type.toLowerCase() === 'post')
{
options.data += options.data?'&':''; // add leading ampersand if `data` is non-empty
options.data += '_token=' + csrfToken; // add _token entry
}
});
$(document).ready(function() {
$('.sortable').sortable();
$('.sortable-save').on('click', function(e) {
e.preventDefault();
var route = $(this).attr('href'),
sortableID = $(this).attr('data-sortable-id');
var data = $('#' + sortableID + ' .sortable-element').map(function() {
return $(this).attr('data-sortable-element-id');
}).get();
$.ajax({
type: 'POST',
url: route,
dataType: 'json',
data: { id_array: data },
success: function(data) {
console.log(data);
}, error: function(data) {
console.log(data);
},
});
});
});
Everything so far is working in terms of the return response in the console, which is Object {category_id: "1", section_id: "1"}. But no matter what I try, I cannot seem to pass through the data map to the controller to use it.
I've tried a bunch of guesswork since I cannot find a single decent tutorial on AJAX in Laravel 5 anywhere, and I've tried things such as adding a $data parameter to the sortOrder() method, I've tried Input::all() and Request::all but it all returns errors (I'm guessing cause it's not an actual form?).
Once I've got the data to be passed through to the controller I'll be able to save the sort order to the database easily enough. But I can't quite get to that stage, any ideas?
EDIT
I should probably note that I do have a HelpCentreArticle model and a HelpCentreArticleRequest request too, here's some of the code from each file in case they are also needed:
HelpCentreArticle.php
class HelpCentreArticle extends Model {
protected $fillable = [
'category_id',
'section_id',
'title',
'content',
'excerpt',
'is_visible',
'sort_order',
'created_by',
'updated_by',
];
}
HelpCentreArticleRequest.php
class HelpCentreArticleRequest extends Request {
/* Authorization ------------------------------ */
public function authorize()
{
return true;
}
/* Validation rules --------------------------- */
public function rules()
{
$rules = [
'title' => 'required|min:3',
'content' => 'required|min:10',
];
return $rules;
}
}
I wasn't sure if I needed to add HelpCentreSectionRequest $request as the last parameter of the sortOrder() method, so I could use $request->all() but it just returns a 422 (Unprocessable Entity) in the console log.
So it appears that the correct way was to use Input::get('id_array'); instead of $_POST['id_array'];, which I tried, but when I originally tried this I wasn't including use Input; at the top of my controller, as I thought this was already accessible, but it wasn't.
Adding use Input;, and using Input::get(); is now working as expected.
Here is the updated code:
AdminHelpCentreArticleController.php
public function sortOrder($category_id, $section_id)
{
/* Query Select ------------------------------- */
$helpCentreCategory = HelpCentreCategory::findOrFail($category_id);
$helpCentreSection = HelpCentreSection::findOrFail($section_id);
/* Variables ---------------------------------- */
$id_array = Input::get('id_array');
$sort_order = 1;
/* Query Update ------------------------------- */
foreach($id_array as $id) {
$helpCentreArticle = HelpCentreArticle::where('id', $id)->first();
$helpCentreArticle->sort_order = $sort_order;
$helpCentreArticle->save();
$sort_order++;
}
/* Return ------------------------------------- */
return ['success' => true];
}
Then you can obviously access success for an if else statement in your jQuery to manipulate the page.
My implementation of UI sortable with Laravel
index.blade.php
...
#foreach($photos as $photo)
<tr data-sortable="{{ $photo->pivot->position }}" data-id="{{ $restaurant->id }}" data-photo-id="{{ $photo->pivot->photo_id }}">
<td>
<i class="fa fa-sort" aria-hidden="true"></i>
</td>
...
</tr>
#endforeach
<script type="text/javascript">
$("#sortable-ui tbody").sortable({
helper: fixHelper,
update: function(event, ui) {
$("#sortable-ui tbody tr").each(function(index){
console.log($(this).data('id')+', '+(index+1));
$.ajax({
url: '{{ route('owner.photo.update.position') }}',
type: 'POST',
data: 'restaurant_id='+$(this).data('id')+'&photo_id='+$(this).data('photo-id')+'&position='+(index+1)
})
.done(function (response) {
console.log(response);
})
.fail(function (jqXhr) {
console.log(jqXhr);
});
});
}
}).disableSelection();
</script>
scripts.js
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
AjaxController.php
public function updatePhotoPosition(Request $request)
{
$restaurant = $this->restaurantRepository->getById($request->get('restaurant_id'));
$photoId = $request->get('photo_id');
$photo = $restaurant
->photos()
->wherePivot('photo_id', $photoId)
->first();
$photo->pivot->position = $request->get('position');
$photo->pivot->save();
}

Categories