laravel API, not fetching data from DB - laravel

This is on production side (on unbtu Digital Ocean server)
"laravel: 5.3"
"php": "5.5.9"
Route path : /route/web.php (not in middleware)
Route::get('api/getsymbol-request','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request){
$symbol = DB::table("symbols")
->where("market_id", $request->market_id)
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
http://yourtradelog.com/api/getsymbol-request?market_id=1 //This is not working url I am getting issue WHY THIS IS NOT WORKING
http://yourtradelog.com/api/getsymbol //This is working url
Database tables
<script>
$(document).ready(function() {
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/getsymbol-request/')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
}
});
});
</script>
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbol:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options'] , null, ['class'=>'symbol_id', 'id'=>'symbol','data-width'=>'60%', 'data-live-search'=>'true'] )!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}

I prefer using route parameters like this (see more in the documentation here):
Routes:
Route::get('api/getsymbol-request/{id}','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request, $id){
$symbol = DB::table("symbols")
->where("market_id", $id)
->get()
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
Please note that the URL has changed to this format:
http://yourtradelog.com/api/getsymbol-request/1

Try to this code:
public function getSymbolRequest(Request $request)
{
$marketID = (int)$request->get('market_id')
$symbol = DB::table('symbols')
->where('market_id', $marketID)
->get(['symbol','id']);
return response()->json($symbol);
}
public function getSymbol()
{
$symbol = DB::table('symbols')
->get(['symbol','id']);
return response()->json($symbol);
}

Related

Laravel problems with redirect

So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}

Laravel 5.3 API not fetching data while using JavaScript on server

Routes: \routes\web.php
Route::get('api/get-market-list','MemberTradesController#getMarketList');
Route::get('api/get-market-list1','MemberTradesController#getMarketListtest');
Controller MemberTradesController
There're two function, getMarketListtest(just for testing on server) and getMarketList (this is for Request $request because, i have used it in dependent select box)
public function getMarketListtest(){
$markets = DB::table("markets")
->pluck("market","id");
return response() -> json($markets);
}
public function getMarketList(Request $request){
$markets = DB::table("markets")
->where("exchange_id", $request->exchange_id)
->pluck("market","id");
return response() -> json($markets);
}
Java scripts :
<script type="text/javascript">
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/get-market-list')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
$("#symbol").empty();
}
});
</script>
View:
<title>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control', 'id'=>'exchange'])!!}
</div>
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
{!! Form::close() !!}
Screenshot of TABLE:
Screenshot of TABLE:
For Function two Link for API result : api/get-market-list
Important information :
when i'm using this in my localhost, its give me result.
first api getMarketListtest() is working, because there is not having : (Request $request)
Error Log of laravel
[Changed code as per you function ]4
You can use $request->input('exchange_id'); instead of $request->exchange_id
Just try to replace this function.
public function getMarketList(\Illuminate\Http\Request $request){
$exchange_id = $request->input('exchange_id');
if(!empty($exchange_id)){
\Log::info('This is working.');
}
$markets = DB::table("markets")
->where('exchange_id', $exchange_id)
->pluck("market","id");
return response()->json($markets);
}
Please comment if any errors.

Datatable service Yajra show blank

i want to add button in Yajra, so i read http://dt54.yajrabox.com/buttons/eloquent.
Im following the step. But still show blank.
nb. if im not using datatable service running well.
Datatables class
namespace App\DataTables;
use App\employee;
use Yajra\Datatables\Services\DataTable;
class EmployeeDataTable extends DataTable
{
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}
public function query()
{
$query = employee::select();
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->ajax('{{ url("Employee/index3") }}')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
]);
}
protected function filename()
{
return 'employeedatatables_' . time();
}
in Controller
use Yajra\Datatables\Facades\Datatables;
use App\DataTables\EmployeeDataTable;
public function index3(EmployeeDataTable $dataTable)
{
return $dataTable->render('employee.users');
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table() !!}
</div>
{!! $dataTable->scripts() !!}
#endsection
If i used firebug, i've got error 304 not modified.
Can you tell me what my mistake,pls ?
Solved.. maybe can help somebody..
this is Column search,and add action using Datatabale service
in Datatables class
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', function ($query) {
return '<i class="glyphicon glyphicon-edit"></i> Edit
<i class="glyphicon glyphicon-minus-sign"></i> Del';
})
->make(true);
}
public function query()
{
$query = employee::select('ID','cNip','vName','vBankbranch');
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
'initComplete' => "function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement(\"input\");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}",
]);
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table([], true) !!}
</div>
#endsection
#section('scripts')
{!! $dataTable->scripts() !!}
#endsection

Laravel 5.2 AJAX filtering by multiple parameters

I am trying to make AJAX filter for my cars catalogue, make logic: "If i have SALES_NAME in request, i'll filter it (add to filter from DB)", but i don't understand how to do it.
I have parameters - Manufacturer, Model, Owner. I want to filter cars by any of them. If i choose only one, owner for example - it will be return all cars of the owner, if i choose Toyota - all toyotas, Or all Toyotas of owner names Bob for example. Here is part of my view:
{!! Form::open(['id'=>'filter']) !!}
{{csrf_field()}}
<div class="form-group col-sm-2">
{!! Form::select('sales_id', ['' => 'Owner'] + $sales, null, ['class'=>'form-control', 'id'=>'sales_id']) !!}
</div>
<div class="form-group col-sm-2">
{!! Form::select('manufacturer_id', ['' => 'Manufacturer'] + $manufacturers, null, ['class'=>'form-control', 'id'=>'manufacturer_id']) !!}
</div>
<div class="form-group col-sm-1">
<button type="button" class="btn btn-start" data-toggle="modal" data-target="#addmanufacturer ">
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
</div>
<div class="form-group col-sm-2">
{!! Form::select('model_id', ['' => 'Model'], null, ['class'=>'form-control', 'id'=>'model_id']) !!}
</div>
<div class="form-group col-sm-1">
<button type="button" class="btn btn-start" data-toggle="modal" data-target="#addmodel">
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
</div>
<button type="submit" class="btn"><i class="fa fa-search" aria-hidden="true"></i></button>
{!! Form::close() !!}
JS:
$('#manufacturer_id').on('change', function(e){
var man_id = e.target.value;
$.get('/admin/getmodels/models?man_id=' + man_id, function(data){
$('#model_id').empty();
$.each(data, function(index, model){
$('#model_id').append('<option value="' + model.id+'">'
+ model.name + ' ' + model.year + '</option>');
});
});
});
$('#filter').submit(function(event) {
event.preventDefault();
$('#cars').empty();
$.post('/admin/getmodels/carfilter', $('#filter').serialize(), function (cars) {
$.each(cars, function (index, car) {
$.post('/admin/getmodels/car', {car_id: car.id}, function (car) {
$('#cars').append('<div class="col-sm-2" id="car'+car.id+'"></div>');
if (car.photos.length > 0) {
$.each(car.photos, function (index, photo) {
if (index == 0) {
$('#car' + car.id).append('<img class="img img-responsive" src="' + photo.file + '">').append('<div class="header header4 text-center">'+car.manufacturer.name+' '+car.model.name+' '+car.model.year+'</div>');
}
});
} else {
$.each(car.modelphoto, function (index, photo) {
if (index == 0) {
$('#car' + car.id).append('<img class="img img-responsive" src="' + photo.file + '">').append('<div class="header header4 text-center">'+car.manufacturer.name+' '+car.model.name+' '+car.model.year+'</div>');
}
});
}
});
});
});
});
Controller, that i'am sure not correct, but it is looks like i want to do:
public function postCarfilter(Request $request)
{
$cars = Car::where('manufacturer_id', $request->manufacturer_id)->where('model_id',$request->model_id)->get();
if ($request->sales_id != ""){
$cars = $cars->where('user_id', $request->sales_id)->get();
}
return Response::json($cars);
}
Models:
class Car extends Model
{
public function user (){
return $this->belongsTo('App\User');
}
public function manufacturer (){
return $this->belongsTo('App\Manufacturer');
}
public function model(){
return $this->belongsTo('App\CarModel');
}
public function photos(){
return $this->morphMany('App\Photo', 'imageable');
}
}
class User extends Authenticatable
{
public function car() {
return $this->hasMany('App\Car');
}
}
class Manufacturer extends Model
{
public function car() {
return $this->hasMany('App\Car');
}
public function model() {
return $this->hasMany('App\CarModel');
}
}
class CarModel extends Model
{
public function car() {
return $this->hasMany('App\Car');
}
public function manufacturer(){
return $this->belongsTo('App\Manufacturer');
}
}
Ok, i got it, i have to use query builder, so new controller:
public function postCarfilter(Request $request)
{
$cars = DB::table('cars');
if ($request->sales_id != ""){
$cars->where('user_id', $request->sales_id);
}
if ($request->manufacturer_id != ""){
$cars->where('manufacturer_id', $request->manufacturer_id);
}
if ($request->model_id != ""){
$cars->where('model_id', $request->model_id);
}
return Response::json($cars->get());
}
Maybe it will be useful for somebody

Passing data from Vue.js request to Laravel 5.3 form

I have two tables: Countries and Cities. Idea is to show the second dropdown when User has selected country and fill it with cities that correspond to selected country.
Unfortunately I cannot figure out how to pass retrieved values to form.
Values retrieved are below the country with id 21 is Norway :)
Selected { "country": "21", "CountrySelected": true, "cities": { "6": "Oslo", "11": "Lillehammer" } }
// My app.js
const app = new Vue({
el: '#events',
data: {
country:'',
CountrySelected: false,
cities:[],
},
methods: {
WhenCountryHasBeenSelected: function(event) {
this.getCities();
this.CountrySelected= true;
},
getCities: function(){
this.$http.get('api/cities/'+this.country).then(function (response) {
this.cities = response.data;
});
}
},
})
//My api.php routes
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$cities=App\City::where('country_id', $country_id)->get()->pluck('name','id');
return $cities;
});
//My blade file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div id="events">
<div class="panel panel-default">
<div class="panel-heading">Select cities by country</div>
<div class="panel-body">
{!! Form::open() !!}
{!! Form::select('country', $countries, null, ['v-model'=>'country', '#change'=>'WhenCountryHasBeenSelected' ,'class'=>'form-control']) !!}
<div v-show="CountrySelected">
{!! Form::select('city',$cities, null, ['class'=>'form-control']) !!}
{!! Form::close() !!}
Selected #{{ $data | json }}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Ended up to use Laravel collection map feature. Mu route looks now like this
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$collection=App\City::where('country_id', $country_id)->get();
$cities=$collection->map(function($city){
return ['id' => $city->id, 'name' => $city->name];
})->toArray();
Long live Laracast forums and bashy :)

Resources