0

I have a multiselect, code is below for the multiselect within my blade.

    {{Form::label('server_id', 'Server')}}      
    <select multiple="multiple" name="server_id[]" id="server_id" class="form-control form-control-md">
        @foreach($servers as $key => $name)
            <option value="{{$key}}">{{$name}}</option>
        @endforeach
    </select

The issue I am running into is I need each of the selected values to be saved within a different row in the database. As you can see right now the key is being saved witihin the server_id[] (Right now it throws an error on save because of unsupported operand type)

But I need each of the items within server_id[] to be saved within their own database entry so they can be easily referred to later. How could one go about doing that, I cant seem to figure it out?

If you need my migrations or controllers I would be happy to add them!

EDIT:: Controller to store after form submission

  public function store(Request $request)
    {
        $this->validate($request, [
            'server_id' => 'required',
        ]);

        $app = Apps::orderby('created_at','desc')->first();
        $app_id = $app->id;

        Helpers::storeAppServer($request, $app_id);

        return redirect('dashboard')->with('success', 'Application Server Updated');
    }

Helper:

public static function storeAppServer(Request $request, $app_id){
        $appserver = new AppServer;
        $appserver->app_id = $app_id;
        $appserver->server_id = $request->input('server_id') + 1;
        $appserver->save();
}
2
  • Post your controller code as well. Commented Jul 9, 2018 at 12:19
  • Controller is added Commented Jul 9, 2018 at 12:26

1 Answer 1

2

As server_id is a multi select field, so it will be posted as an array. And can be treated as array in Helper function storeAppServer. Iterate all values in server_id or $serverIds and save them one by one in database.

Code:

public static function storeAppServer(Request $request, $app_id) 
{
    $serverIds = $request->input('server_ids');
    if (is_array($serverIds)) {
        foreach ($serverIds as $serverId) {
            $appserver = new AppServer;
            $appserver->app_id = $app_id;
            $appserver->server_id = $serverId + 1;
            $appserver->save();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I edited your code slightly so that it worked, I just needed to create a new instance of the AppServer model on each iteration of the foreach also and add app_id to each Instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.