Jack Barham
Jack Barham

Reputation: 3209

Laravel & Eloquent: Correct way to save data simultaneously to two models which requires the id of each of them as the foreign key in the other

When a new page is created part of that data goes to the slugs model (slug url, template type, template id) this is standard on every page, then the rest of the data goes to a template model, in this case called text (simple text page).

The slug is required for example.com/{slug} which grabs the slug_url and looks for the appropriate page/template to produce the correct view and pass the correct data.

Logic:

Slug requires Text id
Text requires Slug id

But as I have to save them at the same time I’m not sure how I get the id of one and pass it to the other, simultaneously, so I came up with this:

  1. Save new Slug
  2. Save new Text (page template)
  3. Update Slug with Text id

Here is the offending code - TextsController:

public function store()
{

    $validator = Validator::make(Input::all(),
        array(
            'title'      => 'required',
            'slug_url'   => 'required',
            'menu_order' => 'required|numeric'
        )
    );

    if($validator->fails()) { 

        Flash::error('Page not created! Please check errors below');
        return Redirect::route('app.pages.index')->withErrors($validator);

    } else {

        $slug = new Slug;
        $slug->user_id     = Auth::id();
        $slug->slug_url    = Input::get('slug_url');
        $slug->type        = Input::get('type');
        $slug->menu_order  = Input::get('menu_order');
        $slug->save();

        $text = new Text;
        $text->user_id = Auth::id();
        $text->slug_id = $slug->id;
        $text->title   = Input::get('title');
        $text->active  = Input::get('active');
        $text->save();

        $slug_update = Slug::where('user_id', Auth::user()->id)->where('slug_url', $slug->slug_url)->first();
        $slug_update->type_id = $text->id;
        $slug_update->update();

        return Redirect::route('app.texts.edit', $text->id);

    }

}

I’m pretty new to Laravel (and development generally) but from what I have see so far, I’m pretty sure there must a cleaner way to do this?

Upvotes: 0

Views: 832

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You can change those lines:

   $slug_update = Slug::where('user_id', Auth::user()->id)->where('slug_url', $slug->slug_url)->first();
   $slug_update->type_id = $text->id;
   $slug_update->update();

into:

   $slug->type_id = $text->id;
   $slug->save();

Upvotes: 1

Related Questions