Search code examples
phpdatabaselaraveldingo-api

Laravel hasMany save


I've two tables to save data to. One of them has foreign key so that I have one-to-many relationship. However, I don't understand how to save data into two table simultaneously. I have one query which contains data for one table and for another that should be attached to first one.

That is the main model

class Site extends Model
{
    protected $fillable = ['path', 'site_link'];

    public $timestamps = false;

    public function features() {
        return $this->hasMany('App\SiteFeature');
    }
}

And this is the sub-model

class SiteFeature extends Model
{
    protected $fillable = ['feature', 'site_id'];

    public $timestamps = false;
}

Right now my controller looks like this

class SiteController extends BaseController
{
    public function index()
    {
        return Site::all();
    }

    public function show(Site $id)
    {
        return $this->response->item($id, new SiteTransformer);
    }

    public function store(Request $request)
    {
        $site = Site::create($request->all());

        return response()->json($site, 201);
    }

I know that it would save it as one piece of data. And I ask you for help me to split data into two tables. In docs I've found the way to store with relationship to an existing model in DB, however I don't have that model at the moment of creation.


Solution

  • Solved that way

    public function store(Request $request)
        {
            $site = Site::create([
                "path" => $request->path,
                "site_link" => $request->link,
            ]);
    
            foreach ($request->features as $feature) {
                $site->features()->save(new SiteFeature(["feature" => $feature]));
            }
    
            return response()->json($site, 201);
        }