Search code examples
phplaravelformbuilder

Fetch an id from pivot table to use in form builder in laravel


I need help to access foreign id in my pivot table to use in form builder select form. I'm trying to create a form when I insert movie and select category then they will be connected when I insert it by fetching category_id from pivot table.

I use many to many relationship and my tables are movies and categories with pivot table category_movie (id, category_id, movie_id).

This is my controller and form.

Controller

    public function store(Request $request)

    {

       $request->user()->authorizeRoles('admin');   

       Movie::create($request->all());

       $categories = Category::pluck('category_name', 'id')->all();

       return view('movies.upload', compact('movies', 'categories'));

    }

View

   <div class="col-md-6">
   {{csrf_field()}}
      {!! Form::open(['method'=>'GET', 'action'=> 'MoviesController@store']) !!}
        <div class="form-group">
           {!! Form::label('name', 'Name:') !!}
           {!! Form::text('name', null, ['class'=>'form-control'])!!}
        </div>
        <div class="form-group">
           {!! Form::label ('', 'Category:') !!}
           {!! Form::select('', [''=>'Choose Categories'] + $categories, null, ['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
           {!! Form::submit('Insert Movie', ['class'=>'btn btn-primary']) !!}
        </div>
      {!! Form::close() !!}
   </div>

Solution

  • First of all you don't need csrf_field() call (Form::open will inject one for you). All you need to do is add logic to your controller to process selected categories. Give your select a name and make it of type multiple (since you have many to many relationship you want user to be able to select multiple categories for a movie):

    <div class="form-group">
        {!! Form::label('categories', 'Category:') !!}
        {!! Form::select('categories', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
    </div>
    

    Then in your controller when storing new movie you can read selected 'categories' from the request and attach them:

    $movie = Movie::create($request->all());
    $movie->categories()->attach($request->get('categories'));
    

    Also store() method is usually accessed via POST route and it returns redirect response to a page where user can view newly created movie (or all movies). To display the form it is better to create a seperate create() method accessed via GET route. And don't forget about validating info in Request - you should either utilize Laravel's FormRequest or use controller's $this->validate() method before inserting anything in your DB.