Skip to content
Advertisement

Laravel | How to use Pivot table with Relationship

I have a question about the relationship. I have an activity model and controller. I guess I searched a lot, I find an attached method for this. But idk how to use it.

I have an activity table like this:

Schema::create('activities', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('company_name');
        $table->string('price');
        $table->string('description');
        $table->timestamps();
    });

And another table is activity_asset like this:

Schema::create('activity_asset', function (Blueprint $table) {
        $table->foreignId('activity_id')->constrained();
        $table->string('image')->nullable();
        $table->string('video')->nullable();
        $table->timestamps();
    });

Now I don’t know how to relate these two tables. What do I want to do? •

  1. I have a form blade. The inputs title,company_name,price,description, video input, file input. (http://prntscr.com/10nyfd1 )

  2. When I create a new activity (title, company_name, price, description) I want to add to video and image URL to add the activity_asset table with activity id.

Short summary: When I create a new activity, how to add other fields add to the activity_asset table with activity_id.

Thanks a lot.

Advertisement

Answer

Try this

First, create an activity.

$activity =  new Activity;
$activity->title = $request->title;
$activity->company_name = $request->company_name;
$activity->price = $request->price;
$activity->description = $request->description;
$activity->save();

foreach ($request->image as $key => $value) {
    $image[] = array(
        'activity_id'         => $activity->id,
        'image'             => $value,
    );
}
ActivityAsset::insert($image);

foreach ($request->video as $key => $value) {
    $video[] = array(
        'activity_id'         => $activity->id,
        'video'             => $value,
    );
}
ActivityAsset::insert($video);

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement