Laravel Eloquent Show Parent and Child Data in Select2 - laravel

I am trying to get parent and child data and show it in Select2.
Model
// JobTypes model
public function jobs()
{
// one type of job has many jobs
return $this->hasMany('App\Jobs', 'id'); // id refer to jobs.id
}
// Jobs model
public function job_types()
{
// one job only belongs to one type of job
return $this->belongsTo('App\jobTypes');
}
Controller
$keyword = $this->request->get('q');
$categories = \App\JobTypes::with(['jobs' => function ($query) use ($keyword) {
$query
->whereHas('job_types')
->orWhereDoesntHave('job_types')
->where('name', 'LIKE', "%$keyword%");
}])->get();
return $categories;
View
$('#goals').select2({
maximumSelectionLength: 2,
ajax: {
url: '{{ url('showjobs') }}',
processResults: function(data) {
return {
results: data.map(function(item) {
return {
id: item.id,
text: item.name,
//childern
children: data.map(function(child){
return {
id: child.id,
text: child.name
}
})
// end childern
}
})
}
}
} });
But the result is not expected.
So, I want all of child data above coming from 'jobs' table. I've tried many times to solve this problem but still stuck here.

Related

Laravel Inertia prop not passing values

When calling an edit function the prop mealService is passing null values and will not populate form fields with values. It looks like the controller isn't loading the model to query the single record. The Create and Store functions work fine.
First time posting. And very new to coding. Please let me know if more info is needed for the question.
edit.vue
export default {
components: {
Head,
Link,
LoadingButton,
SelectInput,
TrashedMessage,
},
layout: Layout,
props: {
mealService: Object,
sites: Array,
},
remember: 'form',
data() {
return {
form: this.$inertia.form({
site_id: this.mealService.site_id,
meal_type: this.mealService.meal_type,
adults: this.mealService.adults,
tally: this.mealService.tally,
}),
}
},
MealServiceController
public function edit(MealService $meal_service)
{
return Inertia::render('MealServices/Edit', [
'mealService' => [
'id' => $meal_service->id,
'site_id' => $meal_service->site_id,
'meal_type' => $meal_service->meal_type,
'adults' => $meal_service->adults,
'tally' => $meal_service->tally,
],
'sites' => Auth::user()->sfa
->sites()
->orderBy('name')
->get()
->map
->only('id', 'name'),
]);
}
MealService Model
class MealService extends Model
{
use HasFactory;
use SoftDeletes;
public function resolveRouteBinding($value, $field = null)
{
return $this->where($field ?? 'id', $value)->withTrashed()->firstOrFail();
}
public function site()
{
return $this->belongsTo(Site::class);
}
public function scopeFilter($query, array $filters)
{
$query->when($filters['search'] ?? null, function ($query, $search) {
$query->WhereHas('site', function ($query) use ($search) {
$query->where('name', 'like', '%'.$search.'%');
});
})->when($filters['trashed'] ?? null, function ($query, $trashed) {
if ($trashed === 'with') {
$query->withTrashed();
} elseif ($trashed === 'only') {
$query->onlyTrashed();
}
});
}
}
Route
Route::get('mealServices/{mealService}/edit', [MealServicesController::class, 'edit'])
->name('mealServices.edit')
->middleware('auth');
In your edit function you are using meal_service while in your route you use mealService
Try naming the one in the edit function mealService too

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 search with select 2 in laravel and ajax?

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

Call to a member function when() on string [duplicate]

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.

The data from input dropdown select2 is not fetch into datatables

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;
}
}
});

Resources