Laravel 5.1: Ajax data is not receiving from server - php

Following is route:
$router->get('/securityquestionlist', [ 'as'=> 'SecurityQuestionListIndexRoute', 'uses'=> 'SecurityQuestionListController#index']);
I have following action in controller class:
public function index()
{
$model = new SecurityQuestionListModel();
$data = $model->select('question','created_at', 'updated_at', 'status')->where('status', 1)
->orderBy('created_at', 'desc')
->paginate(3);
if(Request::ajax()){
return response()->json(['rData' => $data]);
}else{
return view('securityquestionlist.index' /* ,['rData'=> $data]*/ );
}
Following is Ajax code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#IdSQLTable').DataTable({
'ajax' : 'http://localhost:9901/securityquestionlist',
'cache' : false
});
} );
</script>
I am receiving following AJAX response from server:
{"rData":{}}
Can some one guide me, in case of AJAX why $data value is not returning from server. If I disable ajax, and load normal page then value is received on client side and table rows are populated with data. Right now I have made it remarks in :
return view('securityquestionlist.index' /* ,['rData'=> $data]*/ );

Think you have to convert the data to array using toArray()
$rData = $data->toArray();
The send response using
return response()->json(['rData' => $rData]);

Related

How to show id in Resource Routes url?

Update:
This line of code in the frontend was the culprit:
<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">
I had to change it to:
<inertia-link v-if="options.edit" :href="'/admin/gallery/1/edit'">
to make it comply with the laravel resource format for edit, provided by #Babak.
Original Post:
How would I transform this route in web.php:
Route::get('/admin/gallery/edit/{id}', function ($id) {
$data = Gallery::find($id);
return inertia('backend/cms-gallery-edit', ['data' => $data]);
});
to a resource route with its resource controller function:
Route::resource('/admin/gallery', GalleryController::class);
GalleryController.php:
public function edit($id)
{
$data = Gallery::find($id);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Edit:
I've tried both approaches of #Babak's answer, which work for index and create routes but the edit route still throws a 404. It is the only route encompassing an id.
web.php:
Route::resource('/admin/gallery', GalleryController::class)->only('index', 'create', 'edit');
GalleryController.php:
public function edit($gallery)
{
$data = Gallery::find($gallery);
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Inertia passes the id from the frontend via href:
<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">
Browser shows:
GET http://127.0.0.1:8000/admin/gallery/edit/1 404 (Not Found)
There is a fixed structure for laravel resource route method, you can see full list here. For edit page, it will generate something like '/admin/gallery/{gallery}/edit'
You can write it like below:
In your web.php file:
Route::resource('/admin/gallery', GalleryController::class)->only('edit');
And in your controller, name of the resource must be the same as your function's parameter.
public function edit($gallery)
{
$data = Gallery::find($gallery);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Or, you can customize it using parameter method. Refer to here
Route::resource('/admin/gallery', GalleryController::class)->only('edit')->parameters([
'gallery' => 'id'
]);
And your controller
public function edit($id)
{
$data = Gallery::find($id);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}

How to implement DataTable with parameter 'id' in Laravel (DataTables)?

I am trying to pass the ID value from the blade file into ajax so it the data table will be routed and will call the ProductActivities function in ProductController.
Here's my snippet code for show() function in ProductController:
public function show($id)
{
$product = Product::find($id);
$data = Product::with(['user_modify'], 'id', $product->user_modified)
->where('product_id', '=', $id)->first();
$category = Category::select('category_name')
->where('category_id', '=', $data->product_type)
->pluck('category_name')
->first();
if($data->count() > 0){
return view('product.view', compact('data', 'category'));
}else{
Toastr::error('Product cannot be retrieved.', 'Error');
return view('product.index');
}
}
And here's the snippet code of JavaScript for the DataTable initialization in view.blade.php file:
#push('js')
<script>
$(function () {
$("#prod_log_tbl").DataTable({
responsive:true,
stateSave:false,
scrollY:true,
autoWidth: false,
ajax: {{ url('product/activities', [Request::segment(3)]) }},
order:[0, 'desc'],
searchable: false,
sortable:false,
fixedColumns: true
});
});
</script>
#endpush
line of code for route in web.php:
Route::get('product/activities/{id}', 'Master\ProductController#ProductActivities')->name('product/activities/{id}');
snippet code for the ProductActivities() function in ProductController:
public function ProductActivities($id)
{
$dataAct = Activity::all()->where('subject_id', '=', $id);
return Datatables::of($dataAct)->make(true);
}
And here's the result of my current progress:
In the screenshot of result the URL that ajax shows has additional values after the ID which I think causes of the DataTable error.
I don't know How I am getting this error? How can I implement the passing of ID from the view blade file through DataTable ajax into the ProductController?
P.S. I use Yajra/DataTable package for Laravel.
I think you do not need php echo in you Ajax url, route helper syntax is
{{ route('routeName', ['id' => 1]) }}
you need route name and parameter, another way is using url helper
{{ url('product/activities/', [Request::segment(3)]) }}
Beside this if you want to use model refer documentation, using first() will give you only one object, you need a collection, better considering get().

Laravel query string into api call in routes

I have this route
Route::get('/getLocation/{postalCode}', function () {
$response = Http::get('https://theapi');
return $response->json();
});
Sadly this doesn't work
I can reach the api with
https://theapi?PostalCode=xxxx
How can i replicate this in my route to work?
You got double }} there, try delete it so it will be like this:
Route::get('/getLocation/{postalCode}', function () {
$response = Http::get('https://theapi');
return $response->json();
});
Edit:
Add the route parameter to API function parameters
Route::get('/getLocation/{postalCode}', function ($postalCode) {
// do whatever you want to postalCode variable
$response = Http::get('https://theapi', [
'PostalCode' => $postalCode
]);
return $response->json();
});

Post Data not working correctly Laravel

I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});

Resource index parameters

I've wrote a controller to have it's index to output the DataTables plugin data.
A excerpt:
public function index() {
return Datatable::collection(\App\Slip::where('paid', '=', false)->get())
...
->make();
}
and the route:
Route::resource('api/slip', 'SlipsController');
everything works fine, the problem is that this index return only items with paid = false that's right for one view, but for the other view I need all items/rows.
so what's the best practice to make index function cover both cases (all and those with paid = false)?
A post param is the first thing that comes to my mind, but the data is loaded by the DataTables plugin.
Why not?. You need detect your specified view and send some extra param in ajax-request. Like:
$('...').DataTable({
....
"ajax": {
'type': 'GET',
'url': "....",
'data': {paid: false},
},
....
});
Now in action:
public function index(Request $request) {
$paid = $request->input('paid');
$items = [];
if ($paid){
$items = \App\Slip::all()->get();
}else{
$items = \App\Slip::where('paid', '=', false)->get();
}
return Datatable::collection($items)
...
->make();
}

Categories