Home > database >  Laravel how can i store an API parent data with some array child data?
Laravel how can i store an API parent data with some array child data?

Time:04-08

So i want to store Parent data and array child data at the same time in laravel 9 rest api, but i dont even know how to format the array store, i was tried some looping code and still cant. the relationship was one parent has many child. i want to store like this this what i expect store value the parent model it just have name & class, and the child model was foreign parent_id & name. the model

here my controller

public function store(Request $request){
      $this->validate($request, [
        'parent_name' => 'required',
        'class' => 'required',
        'child.*' => 'array',
          ]);
          $child = $request->child;
          $chd = [];
            foreach($child as $cd){
              array_push($chd, Child::create([
                  'child' => $cd,
              ]));
           }
          $this->updates->create($request->all());
          return $this->index();
  }

here the migration :

Schema::create('parent', function (Blueprint $table) {
            $table->increments('id');
            $table->string('parent_name');
            $table->string('class');
            $table->timestamps();
        });
  Schema::create('child', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('parent_id')->unsigned()->index();
            $table->foreign('parent_id')->references('id')->on('parent_id')->onDelete('cascade');
            $table->timestamps();
        });
    }

CodePudding user response:

You may want to try this

    public function store(Request $request) {
        $rules = [
            'parent_name' => 'required|string|max:255',
            'class' => 'required|string|max:255',
            'child' => 'required|array',
            'child.name' => 'required|string|max:255',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return response()->json(['error' => true, 'error_msg' => 'invalid input']);
        }
        DB::beginTransaction();
        $parent = Parent::create([
            'parent_name' => $request->parent_name,
            'class' => $request->class,
        ]);

        foreach ($request->child AS $child) {
            $child = Child::create([
                'parent_id' => $parent->id,
                'name' => $child['name'],
            ]);
        }
        DB::commit();

        return response()->json(['error' => false]);
    }
  • Related