Reputation: 9
There are two tables department
and user
. department
table have name
and id
entities and user
table have name
, id
and department_id
. department_id
have some null
values and the code I wrote is shoes
only null
values. In department
table, sales
has ID = 2
and in user
, table Staff has department_id = 2
...
So I want when I select sales there will be the only staff shoes.
TestController:
namespace App\Http\Controllers;
use App\Departments;
use App\Users;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function prodfunct(){
$department = Departments::all(); // Get data from table
return view('productlist', compact('department')); // Send data to the view
}
public function findUsersName(Request $request){
$data = Users::select('name', 'department_id')
->where('department_id', $request->id)
->take(100)
->get();
return response()->json($data);
}
}
Product.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<center>
<h1>Dependant Drop Down with ajax</h1>
<span>Product Category: </span>
<select style="width: 200px" class="productcategory" id="department_id">
<option value="0" disabled="true" selected="true">-Select-</option>
@foreach($department as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
@endforeach
</select>
<span>Product Name: </span>
<select style="width: 200px" class="name">
<option value="0" disabled="true" selected="true">Product Name</option>
</select>
</center>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.productcategory',function(){
// console.log("hmm it's change");
var cat_id=$(this).val();
//console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findProductName')!!}',
data:{'department_id':cat_id},
success:function(data){
//console.log('success');
console.log(data);
console.log(data.length);
op+='<option value="0" selected disabled>chose product</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].department_id+'">'+data[i].name+'</option>';
}
div.find('.name').html(" ");
div.find('.name').append(op);
},
error:function(){
}
});
});
});
</script>
</body>
</html>
Upvotes: 0
Views: 161
Reputation: 136
If what you are saying is that when you select a particular category you want every users under that category to be displayed. If that's the case then you need to create a relationship between the two models. The Department model will have an eloquent relationship of have many USer models and User model will have a relationship of BelongsTo Department model. Then in your view you create a foreach loop to show every user in a department by writing cat->user->name and that will print all users under that category. If this isnt what you are looking for expatiate more on your issue and possibly send a github repo link.
Upvotes: 1