Как я могу загрузить данные из базы данных, когда выбран класс? - PullRequest
0 голосов
/ 19 февраля 2020
 <div class="float-right">
                    <form>
                        <div class="form-group row">
                            <div class="col-sm-12">

                                <select class="form-control" id="select_id" >
                                     <option> Choose Class </option>
                                    @foreach($allclass as $classs)
                                     <option value="{{$classs->id}}"> {{$classs->class}} </option>
                                        @endforeach
                                </select>

                            </div>
                        </div>
                    </form>

                </div>

Здесь пользователь выбирает класс, а когда пользователь выбирает класс, я хочу просмотреть данные в соответствии с классом.

class SectionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Clas $clas)
    {
        $allclass = Clas::all();
        $sections = $clas->sections;
        return view('admin.section.index')
            ->with('i',$i = 1)
            ->with('sections',$sections)
        ->with('allclass',$allclass);
    }

Это мой раздел Контроллер

   public function clas(){
        return $this->belongsTo(Clas::class);
    }

Это модель раздела, где я сохраняю связь между классом и разделом.

 public function up()
    {
        Schema::create('sections', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('section');
            $table->string('category');
            $table->string('capacity');
            $table->integer('clas_id');
            $table->integer('teacher_id');
            $table->text('note');
            $table->softDeletes();
            $table->timestamps();
        });
    }

Это моя секта ios дБ.

  <table id="userTable" class="table table-bordered table-striped table-vcenter js-dataTable-full-pagination">
                    <thead>
                    <tr>
                        <th class="text-center">S.n</th>
                        <th class="d-none d-sm-table-cell">Section</th>
                        <th class="d-none d-sm-table-cell">Category</th>
                        <th class="d-none d-sm-table-cell">Capacity</th>
                        <th class="d-none d-sm-table-cell">Teacher Name</th>
                        <th class="d-none d-sm-table-cell">Note</th>

                        <th class="text-center">Action</th>
                    </tr>
                    </thead>
                    <tbody>

                    @foreach($sections as $s)
                        <tr id="table-data">
                            <td class="d-none d-sm-table-cell" width="8%">{{1}}</td>
                            <td class="d-none d-sm-table-cell" width="15%">{{$s->section}}</td>
                            <td class="d-none d-sm-table-cell" width="15%"> {{$s->category}}</td>
                            <td class="d-none d-sm-table-cell" width="15%"> {{$s->capacity}}</td>
                            <td class="d-none d-sm-table-cell" width="15%">
                                {{$s->teacher->user->name}}
                            </td>
                            <td class="d-none d-sm-table-cell" width="15%"> {{$s->note}}</td>
                            <td class="d-none d-sm-table-cell" width="20%">
                                <form class="" action="{{ route('section.destroy',$s->id) }}" method="post">
                                    @csrf
                                    @method('DELETE')
                                    <a href="{{$s->trashed()?route('section.restore',$s->id):route('section.edit',$s->id)}}">
                                        <button type="button" class="btn btn-warning mr-5 mb-5 " title="{{ $s->trashed()?'Recover':'Edit'}}">
                                            <i class="{{$s->trashed()?'fa fa-recycle':'fa fa-edit'}}"></i>
                                        </button>
                                    </a>


                                    <button type="submit" class="btn btn-danger mr-5 mb-5" title="{{ $s->trashed()?'Delete':'Trash'}}">
                                        <i class="{{$s->trashed()?'fa fa-trash':'fa fa-minus-circle'}}"></i>
                                    </button>


                                </form>
                            </td>

                        </tr>

                        @php $i++ @endphp

                    @endforeach
                    </tbody>
                </table>

Это моя таблица для просмотра раздела, только когда класс выбран. Как я могу просматривать разделы, только когда какой-то класс выбран.

Извините за мой английский sh.

Теперь я хочу просматривать раздел только тогда, когда выбран класс. Как я могу это сделать?

 $('#select_id').change(function(){
             // alert('hello');
             var cid = $(this).val();
             if(cid){
                 $.ajax({
                     dataType: "json",
                     url: 'getSectionsForClass'+cid,
                     type:"GET",
                     success: function(response){
                         console.log (Object.values(response).length);
                         $('#userTable tbody').empty(); // Empty <tbody>
                         if(response != null){
                             var len = Object.values(response).length;
                         }

                         $.each(response,function(key,value){
                           //  $("#section_id").append('<option value="'+key+'">'+value+'</option>');
                             console.log(key,value);
                         });

                         if(len >0){
                             for(var i=0; i<len; i++){
                                 var section = response[i].section;
                                 var capacity = response[i].capacity;
                                 var category = response[i].category;
                                 var teacher  = response[i].teacher_id;
                                 var note = response[i].note;

                                 var tr_str = "<tr>" +
                                     "<td align='center'>" + (i+1) + "</td>" +
                                     "<td align='center'>" + section + "</td>" +
                                     "<td align='center'>" + capacity + "</td>" +
                                     "<td align='center'>" + category + "</td>" +
                                     "<td align='center'>" + teacher + "</td>" +
                                     "<td align='center'>" + note + "</td>" +
                                     "<td align='center'><button type='submit' class='btn btn-danger mr-5 mb-5'>" + + "</td>" +
                                     "</tr>";

                                 $("#userTable tbody").append(tr_str);
                             }
                         }else{
                             var tr_str = "<tr>" +
                                 "<td align='center' >No record Availasb.</td>" +
                                 "</tr>";

                             $("#userTable tbody").append(tr_str);
                         }

                     },error: (error) => {
                         console.log(JSON.stringify(error));
                   }
              });
             }
         });
 public function getSectionsForClass(Request $request ,$id )
    {
        $section = Section::all()->where('clas_id',$id);
     return  response()->json($section);

    }

Я добавил ajax, но он показывает только первый класс, когда я выбираю другой класс, он показывает ошибку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...