laravel-5mass-assignment

Laravel 5.4 storing mass assignment model and relationship


I'm unsure of the best practice when inserting mass assignment relationships within Laravel 5.4 - I'm new to the framework. The below code is working correctly, however can you tell me is there a way to simply into one line (inserting relationships)?

I've tried to look at 'save()'and 'push()' but it's not working as expected. Would this have an impact if transactions would scale up?

I have a Listing model, with a hasOne relationship:

    public function garage()
    {
       return $this->hasOne('App\Garage', 'post_id');
    }

First of all I have some validation, then I use the following to store, which I want to simplify to one one line of code:

public function store(Request $request)
{
    // Validation has passed, insert data into database
   $listing = Listing::create($request->all());
   $listing->Garage()->create($request->all());
}

Also if I wanted to return the data inserted, how would I do this as the following is only returning the Listing model and not the Garage relationship? Yes I know that I wouldn't do this in a real world application.

return \Response::json([
'message' => 'Post Created Succesfully',
'data' => $listing
]);

Any help is muchly appreciated


Solution

  • Method chaining

    Your store method looks good. You could chain methods though, if you don't need the listing object itself:

    public function store(Request $request)
    {
        // Validation has passed, insert data into database
       $garage = Listing::create($request->all())
                  ->garage()->create($request->all();
    }
    

    But if you need the listing object, it's fine as you did it before!

    Returning relation models

    If you want to return the garage relation model too, you can simply do that by accessing it like a normal class propery:

    return \Response::json([
    'message' => 'Post Created Succesfully',
    'data' => [$listing, $listing->garage] 
                          //Access collection of garage relation ship
    ]);