samedi 3 septembre 2016

Laravel 5 Eloquent insert data to related tables

how to insert data to related tables ? I have two related tables with one-to-many relationship, below is the structure :

Edition table :

public function up()
    {
        Schema::create('edition', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->text('cover')->nullable();
            $table->timestamps();
        });

        //Set FK di kolom id_edition di table Journal
        Schema::table('journal', function(Blueprint $table) {
            $table->foreign('id_edition')->references('id')->on('edition')->onDelete('cascade')->onUpdate('cascade');
        });
    }

Journal table :

public function up()
    {
        Schema::create('journal', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title', 200);
            $table->string('author');
            $table->text('abstract');
            $table->text('file');
            $table->integer('id_edition')->unsigned();
            $table->timestamps();
        });
    }

Edition model :

class Edition extends Model
{
    protected $table = 'edition';

    protected $fillable = [
        'title',
        'cover',
    ];

    public function journal()
    {
        return $this->hasMany('App\Journal', 'id_edition');
    }
}

Journal model :

class Journal extends Model
{
    protected $table = 'journal';

    protected $fillable = [
        'title',
        'author',
        'abstract',
        'file',
    ];

    public function edition()
    {
        return $this->belongsTo('App\Edition', 'id_edition');
    }
}

The edition table supposed to has many journals in it, like an album that has many photos. So, how is the create and the save method would look like ? I did trying and I get this error "Constraint fails", below are the codes :

Controller :

 public function create() {
        return view('journal/create');
    }

    public function store(JournalRequest $request, Edition $edition) {
        $input = $request->all();

        //Input PDF
        if ($request->hasFile('file')) {
            $input['file'] = $this->uploadPDF($request);
        }

        //Insert data journal
        $journal = Journal::create($input);

        return redirect('journal');
    }

The button code that supposed to open a create form in :

<div class="tombol-nav">
<a href="../journal/create?edition=" class="btn btn-primary">Add new Journal to this edition</a>
</div>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire