Home > Blockchain >  How can I resolve Integrity Constraint violation in Laravel
How can I resolve Integrity Constraint violation in Laravel

Time:08-30

Here is my teachers migrations file:

$table->id();
$table->unsignedbiginteger('level_id');
$table->foreign('level_id')->references('id')->on('levels');
$table->string('teacher_name'); 
$table->string('teacher_email')->unique();           
$table->string('teacher_home_phone');
$table->string('teacher_mobile_phone');
$table->string('teacher_work_phone');
$table->string('teacher_home_address');
$table->string('teacher_suburb');
$table->string('teacher_postcode');
$table->string('teacher_username');
$table->string('teacher_password');                      
$table->timestamps();

Here is the levels migrations file:

$table->bigIncrements('id');            
    $table->string('level_name');
    $table->timestamps();
});

Teachers form.blade.php:

<div >                    
    <label for="teacher_levels" >Mention levels Instructor's going to teach </label>                
    <div >                                
        @foreach($levels as $level)                
        <div >
            <input  type="checkbox" name="level_id[]" value="{{@$level->level_id}}" 
                    @if(isset($level->level_id) && @in_array('', @$level->level_id)) {{'checked'}} @endif>
            <label >{{@$level->level_id}}</label>                            
        </div>
        @endforeach
    </div>
</div>

Here is my teachers model.php:

class Teacher extends Model
{
    use HasFactory;
    protected $fillable= ['level_id','teacher_name','teacher_email',
                            'teacher_home_phone','teacher_work_phone',
                            'teacher_mobile_phone','teacher_home_address',
                            'teacher_suburb', 'teacher_postcode',
                            'teacher_username', 'teacher_password',];

    public function levels()
    {
        return $this-> belongsTo(Levels::class, 'level_id');
    }                     
}

This is my levelsmodel.php

class Levels extends Model
{
    use HasFactory;

    public function teacher()
    {
        return $this -> hasMany(Teacher::class);
    }

}

Here is my TeacherController.php:

class TeacherController extends Controller
{
    /**
     * Create a new controller instance
     * 
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard
     * 
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $teachers= Teacher::all();
        $levels = Levels::all();
        return view('admin.teachers.list', compact('teachers', 'levels'));
    }

    /**
     * Show the application dashboard
     * 
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function add()
    {
        $teacher = array();
        $levels = Levels::all();
        return view('admin.teachers.add', compact('teacher', 'levels'));
    }

    /**
     * Store a newly created resource in storage
     * 
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //get form data
        $data = $request->all();

        //Check if teacher is already registered
        $teacher = Teacher::where('teacher_email', $data['teacher_email'])->first();

        //Teacher Check
        if($teacher){
            return redirect()->back()->with('error', 'Teacher is already registered, please check teacher email!');

        }
        

        //Handle Teacher''s level data
        $levels = Levels::all();

        //Check if teacher is already registered
        $user = User::where('email', $data['teacher_email'])->first();

        //User Check
        if($user){
            return redirect()->with('error', 'Teacher email is already registered, please check teacher email');

        }

        //Create Teacher Record
        $teacher = Teacher::create($data);

        //Create User
        $user = User::create([
            'name' => $data['teacher_name'],
            'email' => $data['teacher_email'],
            'password' => Hash::make($data['teacher_password'])
        ]);

        //Assign Above Teacher Role
        $user->assignRole('Teacher');

        //Update teacher column
        $teacher->update([
            'teacher_id' => $teacher->id
        ]);

        if(isset($data['save_close']) && $data['save_close']){
            return redirect()-> route('teacher.index')->with('message', 'Teacher information is saved successfully! ');
        }elseif(isset($data['save_add']) && $data['save_add']){
            return redirect()->back()->with('message','Teacher information is saved successfully!');
        }
    }
    /**
     * Show the form for editing the specified resource
     * 
     * @param int $id
     * @return \Illuminate\Http\Response
     */

     public function edit($id)
     {
        $teachers = Teacher::find($id);
        $levels = Levels::all();
        if($teacher){
            //Teacher Level Convert to Array
            if($teachers->level_id){
                $teachers->level_id = (json_decode($teachers->level_id));
            }
            return view('admin.teachers.edit', compact('teacher', 'levels'));
        }else{
            aboort(404);
        }

        
     }
     
      /**
       * Update the specified resource from url teachers/lists
       * 
       * @param \Illuminate\Http\Request
       * @param int $id
       * @return \Illuminate\Http\Response 
       */
      public function update(Request $request, $id)
      {
        //get form data
        $data = $request->all();

        //Get Teacher Record
        $teacher = Teacher::find($id);
        $teacher->fill($data)->save();

        //Update Password
        if(isset($data['teacher_password']) && $data['teacher_password']){
            $user = User::where('email', $teacher->teacher_email)->first();
            $user->update([
                'password' => Hash::make($data['teacher_password'])
            ]);
        }

        if(isset($data['save_close']) && $data['save_close']){
            return redirect()->route('teacher.index')->with('message', 'Teacher information updated successfully!');
        }elseif(isset($data['save_add']) && $data['save_add']){
            return redirect()->back()->with('message', 'Teacher information updated successfully!');
        }

      }

      /**
       * Remove the specified resource from storage
       * 
       * @param int $id
       * @return \Illuminate\Http\Response
       */
      public function delete($id)
      {
        // Delete the row pointed to by teacher ID
        $teacher = Teacher::findorFail($id);
        //Find User
        $user = User::find($teacher->teacher_id);
        if($user){
            $user->removeRole('Teacher');
            //Delete Teacher
            
            $teacher->delete();
            //Delete User
            $user->delete();
        }else{
            //Delete Teacher
            $teacher->delete();
        }

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

When I click on the save and close buttons I get this error: Integrity constraint violation: 1048 Column 'level_id' cannot be null. I need some help on how can I resolve this issue. One Teacher can teach multiple levels and Multiple levels are taught by one teacher. I want it to be displayed in the listing. attributes of levels tables

CodePudding user response:

Change $level->level_id to $level->id

@foreach($levels as $level)                
    <div >
        <input  type="checkbox" name="level_id" value="{{ $level->id }}" @checked($level->id == old('level_id'))>
        <label >{{ $level->id }}</label>                            
    </div>
@endforeach 
  • Related