I'm trying to load into Select2 the selected value extracted from the DB. Id values are saved in a JSON field that contains the id values or the field '*' that I manage as 'All'.
I want to search first_name and last_name in users table.
AJAX
<script>
$(document).ready(function() {
$('#plaintiffId').select2({
ajax: {
url: '{{ route('admin::reports.plaintiffId') }}',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
first_name: item.user.first_name,
last_name: item.user.last_name,
}
})
};
},
cache: true
}
});
</script>
web.php
Route::get('reports/plaintiffId', 'Admin\ReportController#plaintiffId')->name('reports.plaintiffId');
Controller
public function plaintiffId(Request $request, $term)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = $search->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
return response()->json($data);
}
Model
public function scopeSearch($query, $term)
{
return $query->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
public function plaintiff()
{
return $this->belongsTo(User::class, 'plaintiffId');
}
I get this error in network
You have $term parameter in your controller but you dont send any parameter to your controller, you should send term parameter by ajax to your controller
Related
I want to filter the data in my table. I want if I select the first box it will show the data accordingly and if I select the second box it will show the data accordingly but the problem is that if I select the first box here the data does not show then the second box has to be selected.
Here is my controller code
public function UpazilaWiseReportShow(Request $request){
$data = [];
$data['report_data'] = Report::distric()->status(1)
->where('upazila_id',$request->upazila_id)->where('fiscal_year', $request->fiscal_year)
->get();
return view('adc.reports.upazilla-wise-data', $data);
}
here is my view code
<script>
$(document).ready(function() {
$('#upazila_id').on('change', function() {
getFilterData();
});
$('#fiscal_year').on('change', function (e) {
getFilterData();
});
});
function getFilterData() {
$.ajax({
type: "GET",
data: {
upazila_id: $("[name=upazila_id]").val(),
fiscal_year: $("[name=fiscal_year]").val()
},
url: "{{url('adc/upazila-wise-report')}}",
success:function(data) {
$("#report_data_table").html(data);
}
});
}
</script>
You should check if your $request has your needed fields. So you have to check if your request has these fields. You can use when method for it.
With the code below, you can either select fiscal year or upazila_id or both.
$data['report_data'] = Report::distric()
->status(1)
->when(
isset($request->upazila_id),
function ($query) use ($request) {
$query->where('upazila_id', $request->upazila_id);
}
)
->when(
isset($request->fiscal_year),
function ($query) use ($request) {
$query->where('fiscal_year', $request->fiscal_year);
}
)
->get();
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 1 year ago.
I'm trying to load into Select2 the selected value extracted from the DB. Id values are saved in a JSON field that contains the id values or the field '*' that I manage as 'All'.
I want to search first_name and last_name in the users' table.
AJAX
<script>
$(document).ready(function() {
$('#plaintiffId').select2({
ajax: {
url: '{{ route('admin::reports.plaintiffId') }}',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
first_name: item.user.first_name,
last_name: item.user.last_name,
}
})
};
},
cache: true
}
});
</script>
web.php
Route::get('reports/plaintiffId', 'Admin\ReportController#plaintiffId')->name('reports.plaintiffId');
ReportController.php
public function plaintiffId(Request $request, $term)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = $search->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
return response()->json($data);
}
Report.php
public function scopeSearch($query, $term)
{
return $query->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
public function plaintiff()
{
return $this->belongsTo(User::class, 'plaintiffId');
}
I get this error in the network
When I double-clicked on 500 in the network tab. It open a new tab, I see this error Call to a member function when() on string
$search is a string from request. You can use when only on Query Builder / Eloquent.
I did a multiselect input dropdown using select2. However, I dont really sure how to fetch the data that I call from database in the dropdown so that I can view it in datatable. Here are my codes:
Script for input dropdown select2:
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
dataType: 'json',
delay: 250,
processResults: function ($ethnicity) {
return {
results: $.map($ethnicity, function (item) {
return {
text: item.Bangsa_updated,
id: item.id,
}
})
};
Controller for input dropdown so it will select the input typed:
public function ethnicity(Request $request)
{
$ethnicity = [];
if($request->has('q')){
$search = $request->q;
$ethnicity = DB::table("user")
->select("id","ethnic")
->where('ethnic','LIKE',"%$search%")
->get();
}
return response()->json($ethnicity);
}
The above code only to select the data from database without fetch data to datatable.
The controller below to catch data into datatable (I used this for simple dropdown, however dont know how to change so it is useful for above input dropdown.
public function fnFilter(Request $request)
{
if(request()->ajax())
{
if(!empty($request->dataGender))
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('ethnic', $request->ethnicity)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln', 'Umur', 'Phone', 'Dob','St', 'Country','Zip','Ct','Jantina')
->get();
}
return datatables()->of($data)->make(true);
}
$dataName = DB::table('modified_dpprs')
->select('ethnic','Jantina')
->groupBy('ethnic')
->orderBy('ethnic', 'ASC')
->get();
return response()->json($dataName);
Blade is:
<select id="ethnicity" class=" ethnicity form-control select2-allow-clear" style="width:200px;" name="namaDUN" multiple >
<option value="">Select</option>
My idea is to put the result from controller function ethnicity into function fnFilters. But I dont know how can do it.
you can return response in select2 (controller function) required format
like
$final_array = [];
$ethnicity = DB::table("user")
->select("id","ethnic");
if ($request->search != '') {
$search = $request->search ;
$ethnicity=$ethnicity->where('ethnic','LIKE',"%$search%");
}
// loop the results to make response
foreach($ethnicity->get() as $key => $value):
$final_array[$key]['id'] = $value->id;
$final_array[$key]['text'] = $value->ethnic;
endforeach;
return ['results' => $final_array];
// function ends here
and select 2 tag in blade file like this
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
return query;
}
}
});
public function index(Request $request)
{
$search_book = $request->id;
$proc=DB::select(DB::raw("SELECT * FROM BOOKS WHERE BOOKID = '$Search_book'")
if ($search_book!="") {
return response()->json($proc);
return view('status.status',[
'proc' => $proc
]);
}
How to return 2 data
To determine if a request is an ajax request, you can use the ajax() method on a Request object injected into the controll action:
public function index(Request $request)
{
$results = DB::table('books')
->where('bookid', $request->id)
->get();
if ($request->ajax()) {
return response()->json($results);
}
return view('status.status', [
'proc' => $results
]);
}
I went ahead and fixed the SQL injection vulnerability in your query for you by swapping the query for a proper one. It could still be improved by using a Book model instead of a plain database query, but it is fine this way as well.
The query from your comment can be simplified by replacing the left join. Simply take the sub query as base and right join it with processspj:
DB::table('processtrans as pt')
->leftJoin('processmaster as pm', 'pm.pcm_id', '=', 'pt.pct_pcm_id')
->rightJoin('processspj as ps', 'ps.pc_id', '=', 'pt.pct_pc_id')
->where('pt.pct_pc_id', $request->id)
->select([
'ps.*',
'pm.pcm_bname',
'pt.created_at',
'pt.updated_at',
'pt.pct_id',
'pt.pct_leadtime',
'pt.pct_pcm_id',
'pt.pct_pc_id',
'pt.pct_planfinishdate',
'pt.pct_startdate',
'pt.pct_status',
])
->get();
$(document).ready(function(){
$("#dl_books").change(function()
{
var getValue=$(this).val();
$.ajax({
type: 'GET',
url: '{{route('status')}}',
data: {id:getValue},
success:function(data)
{
//Json for value textbox
$("#txtbookname").text(data[0].pcm_bname);
}
});
});
});
Just save the rendered view in a variable and do a json response:
public function index(Request $request) {
$results = DB::table('books')
->where('bookid', $request->id)
->get();
if ($results) {
$view = view('status.status', [
'proc' => $results
])->render();
return response()->json(['view'=> $view, 'proc' => '$results']);
}
}
How to call the jquery datatable using Ajax post method
same as this link but in post method
public function getAdvanceFilterData(Request $request)
{
$users = User::select([
DB::raw("CONCAT(users.id,'-',users.id) as id"),
'users.name',
'users.email',
DB::raw('count(posts.user_id) AS count'),
'users.created_at',
'users.updated_at'
])->leftJoin('posts', 'posts.user_id', '=', 'users.id')
->groupBy('users.id');
$datatables = app('datatables')->of($users)
->filterColumn('users.id', 'whereRaw', "CONCAT(users.id,'-',users.id) like ? ", ["$1"]);
// having count search
if ($post = $datatables->request->get('post')) {
$datatables->having('count', $datatables->request->get('operator'), $post);
}
// additional users.name search
if ($name = $datatables->request->get('name')) {
$datatables->where('users.name', 'like', "$name%");
}
return $datatables->make(true);
}
When you initialize the DataTable on javascript, set the ajax method to post like this:
"type": "POST"
(adding it on the example that you linked):
ajax: {
url: 'http://datatables.yajrabox.com/eloquent/advance-filter-data',
type: "POST",
data: function (d) {
d.name = $('input[name=name]').val();
d.operator = $('select[name=operator]').val();
d.post = $('input[name=post]').val();
}
},
and then on laravel you should be able to access the inputs in form of
$datatables->request->post('post')