Skip to content
Advertisement

Laravel Form displaying correct data but storing incorrect values in DB

I have come across a bug on my website and I am baffled as to how to fix it.. basically I have a view to create courses, I type a course title and secondly assign an instructor to that course and click save. But when i return to my index page.. the instructor i assigned is completely different. It appears there must be an issue with my select but I am not sure how to go about fixing it.. I am new to laravel so any help is greatly appreciated.

I have added a picture to try to further explain my issue, here i have selected an instructor –

enter image description here

And when i return to my index page, the newly created course ‘test’ has the admin user assigned… I am very confused –

enter image description here

create.blade.php

@extends('layouts.app')

@section('content')
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Create Course</div>
                <div class="card-body">

                        <form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
                            @csrf

                            <div class="form-group">
                                    <label class="required" for="name">Course Title</label>
                                    <input class="form-control" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
                                    @if($errors->has('name'))
                                    <div class="invalid-feedback">
                                        {{ $errors->first('name') }}
                                    </div>
                                @endif
                            </div>


                            <div class="form-group {{ $errors->has('instructors') ? 'has-error' : '' }}">
                                <label class="required" for="name">Instructors</label>
                                    <select class="form-control select2" name="instructors[]" id="instructors" multiple>
                                        @foreach($instructors as $id => $instructors)
                                            <option value="{{ $id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructors }}</option>
                                        @endforeach
                                    </select>
                            </div>

                            <div class="form-group">
                            <button class="btn btn-danger" type="submit">
                                Save
                            </button>
                        </div>
                    </div>

                    </form>
                </div>
            </div>
            @endsection

index.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <p>
            @can('create_courses')
                <a href="{{ route('admin.courses.create') }}"><button type="button" class="btn btn-success">Create Course</button></a>
            @endcan('create_courses')
            </p>
            <div class="card">
                <div class="card-header">Courses</div>

                <div class="card-body">


                    <div class="table-responsive">
                    <table class="table">
                        <thead>
                          <tr>
                            <th>ID</th>
                            <th>Course Title</th>
                            <th>Instructor</th>
                            <th></th>
                            <th></th>
                            <th></th>
                          </tr>
                        </thead>
                        <tbody>
                        @foreach($course as $course)
                            <tr>
                            <th scope="row">{{ $course->id }}</th>
                            <td>{{ $course->title}}</td>
                           <td>{{ implode (', ', $course->instructors()->pluck('name')->toArray()) }}</td> 
                            <td> 
                                    @can('edit_courses')
                                    <a class="btn btn-xs btn-secondary" href="{{ route('admin.modules.index', $course->id) }}">
                                        Modules
                                    </a>
                                    @endcan
                            </td>
                            <td>
                                    @can('edit_courses')
                                    <a class="btn btn-xs btn-primary" href="{{ route('admin.courses.edit', $course->id) }}">
                                        Edit
                                    </a>
                                    @endcan
                            </td>
                            <td>
                                    @can('delete_courses')
                                    <form action="{{ route('admin.courses.destroy', $course->id) }}" method="POST" onsubmit="return confirm('Confirm delete?');" style="display: inline-block;">
                                        <input type="hidden" name="_method" value="DELETE">
                                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                        <input type="submit" class="btn btn-xs btn-danger" value="Delete">
                                </form>
                                @endcan  
                                </td>
                            </tr>
                        @endforeach

                        </tbody>
                      </table> 
                    </div>
                </div>
            </div>
        </div>
        <!-- <div class="col-md-2 col-lg-2">
                <div class="list-unstyled">
                    <a href=""class="list-group-item">Courses</a>
                    <a href=""class="list-group-item">Modules</a>
                </div>
        </div> -->
    </div>
</div>
@endsection

CoursesController;

<?php

namespace AppHttpControllersAdmin;

use Gate;
use AppUser;
use AppCourse;
use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesInput;


class CoursesController extends Controller
{
    public function __construct()
    {
        //calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
        $this->middleware('auth');
    }

    public function index()
    {
        if(Gate::denies('manage_courses')){
            return redirect(route('home'));
        }

        $courses = Course::all();
        return view('admin.course.index')->with('course', $courses); //pass data down to view
    }

    public function create()
    { 
        if(Gate::denies('create_courses')){
            return redirect(route('home'));
        }

        $instructors = User::whereHas('role', function ($query) { 
            $query->where('role_id', 2); })->get()->pluck('name'); //defining instructor variable to call in create.blade.php. Followed by specifying that only users with role_id:2 can be viewed in the select form by looping through the pivot table to check each role_id 

        return view('admin.course.create', compact('instructors')); //passing instructor to view
    }

    public function store(Request $request)
    {
        $course = Course::create($request->all()); //request all the data fields to store in DB
        $course->instructors()->sync($request->input('instructors', [])); //input method retrieves all of the input values as an array

        if($course->save()){
            $request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
        }else{
            $request->session()->flash('error', 'There was an error creating the course');
        }

        return redirect()->route ('admin.courses.index');
    }

    public function destroy(Course $course)
    {
        if(Gate::denies('delete_courses'))
        {
            return redirect (route('admin.course.index'));
        }

        $course->delete();
        return redirect()->route('admin.courses.index');
    }

    public function edit(Course $course)
    {
        if(Gate::denies('edit_courses'))
        {
            return redirect (route('admin.courses.index'));
        }

        $instructors = User::whereHas('role', function ($query) { 
            $query->where('role_id', 2); })->get()->pluck('name');

        //return view('admin.course.edit', compact('instructors'));

        return view('admin.course.edit', compact('instructors'))->with([
             'course' => $course
        ]);
    }

    public function update(Request $request, Course $course)
    {
        $course->update($request->all());

        if ($course->save()){
            $request->session()->flash('success', $course->title . ' has been updated successfully.');
        }else{
            $request->session()->flash('error', 'There was an error updating ' . $course->title);
        }
        return redirect()->route('admin.courses.index');
    }

    public function show(Course $course)
    {
        return view('admin.course.show', compact('course'));
    }

}

Referring to latest comment – enter image description here

Advertisement

Answer

you are updating data with key not id

try this

in controller

 $instructors = User::whereHas('role', function ($query) { 
            $query->where('role_id', 2); })->select('id','name')->get(); 

in blade

you will need instructors->id to update right value

@foreach($instructors as $id => $instructor)
<option value="{{ $instructor->id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructor->name }}
</option>
@endforeach
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement