Laravel Dynamic Dependent Dropdown - laravel

I need to add a Laravel Dynamic Dependent Dropdown. Im confused..
In my database, i have both categories and their childrens.
Account_id =0 => Categorie
Account_id =1 => Sub Categorie of category or subcategory with id =1
Account_id =2 => Sub categorie of category or subcategory with id =2
This is my actual code :
Method:
public function index()
{
$categories = Account::where('account_id', '=', 0)->get();
$allCategories = Account::where('account_id', '=', 0)-
>pluck('account_name','id');
return view('Account.list',compact('categories', 'allCategories')); //
set the path of you templates file.
}
public function children(Request $request)
{
return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}
View:
<div class="form-group">
{!! Form::label('account_id', 'Parent Category:')!!}
{!! Form::select('account_id', $allCategories, ['placeholder' =>
'Choose Category'])!!}
</div>
<div class="form-group">
{!! Form::label('children', 'Child category:')!!}
{!! Form::select('children', [], null, ['placeholder' => 'Choose child
category'])!!}
</div>
Route:
Route::get('/categories', [
'uses' => 'AccountController#index',
'as' => 'categories'
]);
Route::get('/categories/children', [
'uses' => 'AccountController#children',
'as' => 'categories.children'
]);
JS:
<script>
$('#account_id').change(function(e) {
var parent = e.target.value;
$.get('/categories/children?account_id=' + account_id, function(data) {
$('#children').empty();
$.each(data, function(key, value) {
var option = $("<option></option>")
.attr("value", key)
.text(value);
$('#children').append(option);
});
});
});
</script>

try this first create new route
Route::post('subchildren/youcontroller', [
'as' => 'children.categories',
'uses' => 'youUrlController\yourController#childrenCategory',
]);
next create route go to controller create new method
public function childrenCategory(Request $request)
{
try {
$subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
return response()->json(['subCategory' => $subCategory], 200);
} catch (Exception $e) {
return response()->json(['error' => 'Error'], 403);
}
}
next in your view
<div class="form-group m-b-40">
<select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>
next in your javascript
jQuery(document).ready(function($) {
$('#FirstSelect').change(function () {
$('#subCategory').empty();
var Category = $(this).val();
datos = {
tipo : Category
},
$.ajax({
url: '{{ route('children.categories') }}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: datos,
success: function (argument) {
arreglo = {id:"a", tipo:""};
argument.detalles.unshift(arreglo);
$.each(argument.subCategory, function(index, el) {
var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
$('#subCategory').append( opcion );
});
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
});
});

Related

Edit Data using Ajax in Laravel

I'm trying to get data in form usin ajax
So I'm using the following code :
$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url:"castingss/"+id+"/edit",
dataType:"json",
success:function(html){
$('#casting_name').val(html.data.casting_name);
$('#casting_cin').val(html.data.casting_cin);
$('#casting_email').val(html.data.casting_email);
$('#casting_phone').val(html.data.casting_phone);
$('#casting_age').val(html.data.casting_age);
$('#casting_sexe').val(html.data.casting_sexe);
$('#casting_city').val(html.data.casting_city);
$('#casting_address').val(html.data.casting_address);
$('#store_image').html("<img src={{ URL::to('/') }}/images/" + html.data.casting_photo + " width='70' class='img-thumbnail' />");
$('#store_image').append("<input type='hidden' name='hidden_image' value='"+html.data.casting_photo+"' />");
$('#hidden_id').val(html.data.id);
$('.modal-title').text("Edit New Record");
$('#action_button').val("Edit");
$('#action').val("Edit");
$('#formModal').modal('show');
}
})
});
When I execute I get this exception :
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
I understood that the url is undefind , how can I sove this problem ?
EDIT
I was following this tutorial enter link description here
they don't define a route for this URL
EDIT2
Route::get('/', function () {
return view('auth.login');
});
//auth route for both
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
});
// for Manager de filial
Route::group(['middleware' => ['auth', 'role:manager_de_filiale']], function() {
Route::get('/dashboard/myprofile', 'App\Http\Controllers\DashboardController#myprofile')->name('dashboard.myprofile');
});
// for AccountManager
Route::group(['middleware' => ['auth', 'role:account_manager']], function() {
Route::get('/dashboard/postcreate', 'App\Http\Controllers\DashboardController#postcreate')->name('dashboard.postcreate');
});
Route::group(['middleware' => ['auth']], function() {
Route::get('/castings', 'App\Http\Controllers\DashboardController#casting')->name('dashboard');
});
//for adding a new casting
Route::group(['middleware' => ['auth']], function() {
Route::post('castingss', 'App\Http\Controllers\CastingController#store');
});
Route::get('castingss', 'App\Http\Controllers\CastingController#getdata');
Route::get('castingss', [App\Http\Controllers\CastingController::class, 'getdata'])->name('castingss.getdata');
My Controller:
function getdata(Request $request)
{
if(request()->ajax())
{
return datatables()->of(Casting::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('Casting.castingss');
}
public function edit($id)
{
if(request()->ajax())
{
$data = Casting::findOrFail($id);
return response()->json(['data' => $data]);
}
}
Any Idea ?
I SOLVE IT BY adding that to my web page :
Route::get('castingss/{id}/edit', [App\Http\Controllers\CastingController::class, 'edit']);

How to pass data from controller to view using AJAX

I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');

How to get value of Selected items of Select2 when submitted?

What options I should set to get the value of the options when I submit the form?
I am using Select2. I have given the code I have to setup the select2, controller that returns the data, the html code that renders the element.
Html Code to add the select2 element:
<div class="form-group row"><label class="col-lg-2 col-form-label">Keyword</label>
<div class="col-lg-10">
<select class="form-control w-50" name="keywords[]" id="keyword" multiple="multiple">
</select>
<span class="form-text m-b-none">One or multiple keywords</span>
</div>
</div>
Datasource is an Ajax call:
$(document).ready(function() {
$('#keyword').select2({
tags: true,
tokenSeparators: [',', ' '],
placeholder: 'Select keyword',
ajax: {
url: 'https://rankypro.dev/app/json/keywords',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});
Controller:
public function getKeywords(Request $request){
$search = $request->search;
if($search == ''){
$keywords = Term::orderby('name','asc')
->select('id','name')
->where('taxonomy','keyword')
->limit(5)
->get();
}else{
$keywords = Term::orderby('name','asc')->select('id','name')
->where('taxonomy','keyword')
->where('name', 'like', '%' .$search . '%')
->limit(5)
->get();
}
$results = array();
foreach($keywords as $keyword){
$results[] = array(
"id"=>$keyword->id,
"text"=>$keyword->name
);
}
echo json_encode($results);
exit();
}
I am testing with:
public function store(Request $request)
{
dd($request->keywords);
}
I get the following:
array:2 [
0 => "Tools"
1 => "SEO"
]
I actually need ids of the keywords. Would you please give some hints how can I get that.
I think their is some issue in rendering data. Try to replace
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
With
processResults: function (data) {
return {
results: data.item
};
},
select2 automatically render id and name.

how to insert data to database with vue and laravel

i trying to create a crud system using vue js and laravel.
i already create api route and more...
but when i click submit i got message 405 (Method Not Allowed)
here my AddArtist.vue file
<form #submit.prevent="add">
<input type="text" class="form-control" v-model="artist.name" placeholder="Artist Name">
<button class="btn btn-success" type="submit">Save</button>
</form>
<script>
export default {
data: function () {
return {
errors: [],
image: '',
artist: {
name: '',
}
}
},
methods: {
add() {
axios.post('/api/artist/store-artist', this.$data.artist)
.then((response) => {
alert('Success add Artist')
console.log(response)
})
},
},
mounted() {
console.log('Add Artist Mounted.')
}
}
</script>
and my api.php route
Route::group(['middleware' => 'cors'], function(){
Route::post('addartist/store-artist', 'ArtistController#store');
});
and here my controller ArtistController.php
public function store(Request $request)
{
$input = $request->all();
dd($input);
}
and the last is my model Artist.php
class Artist extends Model
{
protected $table = 'artist';
protected $fillable = ['artist_name', 'date_birth', 'cover', 'gender'];
}
that is typo error:
change addartist/store-artist to artist/store-artist in route
Your api is :
Route::group(['middleware' => 'cors'], function(){
Route::post('addartist/store-artist', 'ArtistController#store');
});
and you are doing :
axios.post('/api/artist/store-artist', this.$data.artist)
.then((response) => {
alert('Success add Artist')
console.log(response)
})

I can not save values using POST method - laravel vue

I'm trying to save the data I send from the Event view. in the storeEvent method of the EventController driver but it gives me error 422 and I can not find the problem so far.
The Event model has a many-to-many relationship with the Categories model, and Event also has a many-to-many relationship with the Coins model, which is why I occupy vue-multiselect since the user can select several categories or several coins for the same event
Event.vue
<template>
<form v-on:submit.prevent="createdEvent" class="form-horizontal">
<div class="form-group row">
<label>Titulo</label>
<input type="text" name="title" maxlength="25" v-model="title">
</div>
<div class="form-group row">
<label>*Cryptodivisas</label>
<multiselect v-model="coinvalue" :options="coins"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="form-group row">
<label>*Categoría</label>
<multiselect v-model="categoryvalue" :options="categories"
:multiple="true" label="name"
track-by="id" placeholder="Seleccione">
</multiselect>
</div>
<div class="col-sm-12">
<button class="btn" type="submit">Crear evento</button>
</div>
</form>
<script>
import Multiselect from 'vue-multiselect';
export default {
components: {
Multiselect,
},
props: ['auth'],
data () {
return {
user: {},
title: '',
coins: [],
coinvalue: [],
categories: [],
categoryvalue: [],
}
},
created() {
this.getCoins();
this.getCategories();
},
mounted() {
this.user = JSON.parse(this.auth);
},
methods: {
getCoins(){
let urlCoin = '/dashboard/coins';
axios.get(urlCoin)
.then((response) => {
this.coins = response.data;
})
.catch((err) => {
})
},
getCategories(){
let urlCategories = '/dashboard/categories';
axios.get(urlCategories)
.then((response) => {
this.categories = response.data;
})
.catch((err) => {
})
},
createdEvent(){
let urlEvent = '/dashboard/newEvent';
const eventData = {
'id' : this.user.id,
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
}
console.log(eventData);
axios.post(urlEvent, eventData)
.then((response) => {
console.log(ok);
})
.catch((err) => {
console.log(err.response.data);
})
}
</script>
storeEvent (EventController)
public function storeEvent(Request $request)
{
$this->validate($request, [
'title' => 'required|max:25',
'coin' => 'required',
'category' => 'required',
]);
$userAuth = Auth::user()->id;
$userEvent = $request->id;
if($userAuth === $userEvent){
$event = new Event;
$event->user_id = $userEvent;
$event->title = $request->title;
if($event->save()){
$event->coins()->attach($request->coin);
$event->categories()->attach($request->category);
return response()->json([
'status' => 'Muy bien!',
'msg' => 'Tu evento ya fue creado con éxito.',
], 200);
}
else {
return response()->json([
'status' => 'Error!',
'msg' => 'No pudimos crear tu evento.',
], 401);
}
}
}
I think the problem may be when I assign the values to the coin () -> attach () and category () -> attach () section, but I have no idea how to solve it due to my inexperience in the tool.
The system was made entirely in Laravel and it worked without problems, now that it is being updated with Vue it began to give inconveniences.
Any ideas? I occupy Laravel 5,6, Vuejs 2, Axios and Vue-multiselect 2
Try sending form data
Here is the example for you.
var urlEvent = '/dashboard/newEvent';
var form_data = new FormData();
form_data.append('id',this.user.id);
form_data.append('title',this.title);
for(let coin of this.coinvalue)
form_data.append('coin[]', coin);
for(let category of this.categoryvalue)
form_data.append('category[]', category);
axios(urlEvent,{
method: "post",
data: form_data
})
.then(res => {
console.log(ok);
})
.catch(err => {
console.log(err.response.data);
});
If this stills gives you a 422 status code (Unprocessable entities). Then try returning $request in you controller. And check what data are actually send to the controller and what your validation is.
422 means validation error so do a console.log or inspect the element on axios call and check that :
'title' : this.title,
'coin' : this.coinvalue,
'category' : this.categoryvalue,
Are not empty, cause right now some data from above is missing since its a 422 validation exception.

Resources