Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

slickness's avatar

Many to Many Relationsship, store data in different tables

i have 3 tables (interest, user, itag) with a many to many relationship and pivot tables.

Now I want to store several itags with a multiple input field of an array and store the relationships. The relationship between interest and itags and the relationship between interest and user.

The pivot table´s look like this:

        Schema::create('interest_itag', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('interest_id')->unsigned();
            $table->foreign('interest_id')->references('id')->on('interests');
            $table->integer('itag_id')->unsigned();
            $table->foreign('itag_id')->references('id')->on('itags');
        });

This is my Controller:

 public function store(Request $request)
    {

        $this->validate($request, [
            'name' => 'required|min:3|max:15',
        ]);

        $interest = new Interest();
        $interest->name = $request->name;

        $interest->save();

        $interest->itags()->sync($request->itags, false);

        return back()->with('success', lang::get('messages.newinterest'));
    }

How can I validate and save several itags? And how can I save the relationship between the user and the interest?

0 likes
1 reply
slickness's avatar
slickness
OP
Best Answer
Level 2

I solved the problem:

 public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:3|max:15',
            'itag' => 'required'
        ]);

        $interest = new Interest();
        $interest->name = $request->name;

        $interest->save();

        if($interest)
        {
            $itagNames = explode(',' ,$request->get('itag'));
            $itagIds = [];
            foreach($itagNames as $itagName)
            {
                //$interest->itags()->create(['itag'=>$tagName]);
                //Or to take care of avoiding duplication of Tag
                //you could substitute the above line as
                $itag = Itag::firstOrCreate(['itag'=>$itagName]);
                if($itag)
                {
                    $itagIds[] = $itag->id;
                }

            }
            $interest->itags()->sync($itagIds);
        }

        $user = Auth::user();
        $interest->user()->sync($user);


        return back()->with('success', lang::get('messages.newinterest'));
1 like

Please or to participate in this conversation.