jeudi 8 août 2019

Storing Primary Key of table to Foreign key of another table -- Laravel 5.8

I want to store the primary key of department table to section table.

Migration

Schema::create('tbl_department', function (Blueprint $table) {
      $table->string('id')->primary();
      $table->string('department_name')->nullable();
      $table->softDeletes();
      $table->timestamps();
    });

 Schema::create('tbl_section', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->string('department_id');
            $table->foreign('department_id')
                        ->references('id')
                        ->on('tbl_department')
                        ->onDelete('cascade')
                        ->onUpdate('cascade');
            $table->string('section_name')->nullable();
      $table->softDeletes();
      $table->timestamps();
    });

Department Model

class DepartmentModel extends Model
{
    protected $table = 'tbl_department';
    protected $fillable = ['department_name'];

public function section () {
    return $this->hasMany('App\SectionModel', 'department_id'); 
}

Section Model

class SectionModel extends Model
{
  protected $table = 'tbl_section';
    protected $fillable = ['department_id', 'section_name'];



    public function department () {
        return $this->belongsTo('App\DepartmentModel', 'department_id');    
    }

Controller

public function store(Request $request)
  {
    $request->validate ([
            'department' => 'required',
            'section' => 'required'
        ]);

        DepartmentModel::create ([
            'department_name' => $request->department,
    ]);

    SectionModel::create ([
            'section_name' => $request->section,
    ]);

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire