简体   繁体   中英

how to add an extra column to pivot table via checkbox in laravel

im trying to build an podcast site but getting stuck at the backend, i wanna create some speakers for the podcasts, and then it should be also able to put them as "is_moderator". I tryed to do that via a pivot table because one speaker can be moderator for a lot of tracks and also in the other direction.

This is my SpeakerController

    public function store(Request $request)
    {
        $speaker = new Speaker();
        $speaker->first_name = $request->first_name;
        $speaker->last_name = $request->last_name;
        $speaker->save();
        $speaker->tracks()->attach($request->input('tracks'));
        $speaker->tracks()->attach($request->input('is_moderator'));
        return redirect()->back();
    }

This is my TrackController


        public function store(Request $request)
    {
        $request->track_data->storeAs('public/tracks', $request->track_data->getClientOriginalName());
        $track = new Track();
        $track->title = $request->track_title;
        $track->description = $request->track_description;
        $track->data = $request->file('track_data')->getClientOriginalName();
        $track->season_id = $request->season_id;
        $track->save();
        $track->topics()->attach($request->input('topics'));
        $track->speakers()->attach($request->input('speakers'));
        return redirect()->route('admin.home');
    }

Speaker Model


    class Speaker extends Model
{
    use HasFactory;

    protected $table = 'speakers';

    protected $primaryKey = 'id';

    protected $fillable = [
        'first_name',
        'last_name'
    ];

    public function tracks():BelongsToMany
    {
        return $this->belongsToMany(Track::class, 'speakers_tracks', 'speaker_id', 'track_id');
    }
}

Track Model


    protected $table = 'tracks';

    protected $primaryKey = 'id';

    protected $fillable = [
            'title',
            'description',
            'data',
            'season_id',
        ];



    public function season(): BelongsTo
    {
        return $this->belongsTo(Season::class);
    }

    public function speakers(): BelongsToMany
    {
        return $this->belongsToMany(Speaker::class, 'speakers_tracks', 'track_id', 'speaker_id');
    }

    public function topics(): BelongsToMany
    {
        return $this->belongsToMany(Topic::class, 'topics_tracks', 'track_id', 'topic_id');
    }

}

setup for the view


        <form action="{{ route('admin.speakerStore') }}" method="post" enctype="multipart/form-data" id="speaker-form">
        @csrf
        <label for="first_name">First Name</label>
        <input type="text" name="first_name" id="first_name">
        <label for="last_name">Last Name</label>
        <input type="text" name="last_name" id="last_name">
        <input type="checkbox" value="1" name="is_moderator" id="is_moderator">  is Moderator?
        <div class="container mt-5">
            <label>tracks</label>
            <select class="form-select" multiple="multiple" name="tracks[]">
            @foreach($tracks as $track)
                <option value="{{$track->id}}">{{$track->title}}</option>
                @endforeach
            </select>
        </div>
        <button type="submit">submit</button>
    </form>

And the Schema for my Pivot table


        public function up()
    {
        Schema::create('speakers_tracks', function (Blueprint $table) {
            $table->id('id');
            $table->integer('speaker_id')->unsigned();
            $table->integer('track_id')->unsigned();
            $table->boolean('is_moderator');
            $table->timestamps();
        });
    }

Just needs to save the boolean value of the moderator field and that will not work so if anyone of you has some good explanation about how to use a pivot table in connection to an non existing table i would be very thankful.

Thanks in advance:peace:

in your relation you have to use withPivot , https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

for instance:

public function tracks():BelongsToMany
{
    return $this->belongsToMany(Track::class, 'speakers_tracks', 'speaker_id', 'track_id')->whitPivot('is_moderator');
}

Then, in your controller you have to do this:

public function store(Request $request)
{
    $speaker = new Speaker();
    $speaker->first_name = $request->first_name;
    $speaker->last_name = $request->last_name;
    $speaker->save();
    $data = [];
    foreach($request->input('tracks') as $trackId) {
        $data[$trackId] = ['is_moderator' => $request->input('is_moderator')];         
    }
    $speaker->tracks()->attach($data);
    return redirect()->back();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM