jeudi 20 octobre 2016

Laravel - Create and Attach - Many to Many relationship

I need some help.

I have these tables: users, buys and codecs. I have a many-to-many relationship: buys, codecs, buy_codec

Tables

Schema::create('codecs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('buys', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('name');
});   

Schema::create('buy_codec', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('buy_id')->unsigned();
    $table->foreign('buy_id')->references('id')->on('buys')->onDelete('cascade');

    $table->integer('codec_id')->unsigned();
    $table->foreign('codec_id')->references('id')->on('codecs')->onDelete('cascade');

    $table->timestamps();
});    

Models

class Codec extends Model
{
    protected $guarded = ['id'];
    public function buy() {
        return $this->belongsToMany('App\Buy');
    }
}

class Buy extends Model
{
    protected $guarded = ['id'];
    public function codec() {
        return $this->belongsToMany('App\Codec');
    }
}

class User extends Authenticatable
{
    public function buy() {
        return $this->hasMany('App\Buy');
    }
}

I want to populate the buy table with the user_id, and to attach the codecs from the codecs table.

This is the buy create form.

{!! Form::open(['method'=>'POST', 'action'=>['UserBuyController@store', $usr->id]]) !!}

    <div class="form-group">
        {!! Form::label('name', 'Name:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-font"></i></span>
            {!! Form::text('name', null, ['class'=>'form-control']) !!}
        </div>
    </div>

    <div class="form-group">
        {!! Form::label('codecs', 'Outbound Codecs:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-language"></i></span>
            {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
        </div>
    </div>

    {!! Form::submit('Submit', ['class'=>'btn btn-info']) !!}

{!! Form::close() !!}

Everything works fine, if i don't attach the codecs.

UserBuyController

class UserBuyController extends Controller
{
    public function create($userId)
    {
        $codecs = Codec::lists('name', 'id');
        $usr = User::findOrFail($userId);
        return view('buy.create', compact('usr', 'codecs'));
    }

    public function store($userId, Request $request)
    {
        $usr = User::findOrFail($userId)->buy()->create($request->all());
        return view('buy.index');
    }
}

How can I create the buy record(because i need the buy id) and than attach the codecs in the pivot table?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire