mysqllaravel-5.1laravel-schema-builder

How to add selected item into mysql database Laravel Schema Builder?


I used webpatser/laravel-countries

in my controlleer

$countries= DB::table('countries')->lists('name');

to select country list in my form i got all the country

{!! Form::select('country',$countries,null) !!}

in my schema now i have like this

$table->string('country');

i can select the country but when i submit country column blank. any idea ?


Solution

  • Edit 2:

    Your insert need to look like this:

    DB::table('users')->insert(
        ['country' => 'Canada']
    );
    

    https://laravel.com/docs/5.2/queries#inserts


    Edit: if you want to submit the string of the country name then you need the string to be the key in your array. Like this:

    $countries= DB::table('countries')->lists('name', 'name');
    

    That's not typical use of a database relationship though. I'd expect the user table to have a country_id integer field that matches the id field in countries. That's what my original answer (below) covers.


    Original:

    You'll want the id in your $countries array. I bet right now your ids are off by one, starting at 0 instead of 1 like in your DB.

    $countries= DB::table('countries')->lists('name', 'id');
    

    There are different ways to save relations in laravel, but I actually prefer to skip that when possible and save directly to the country_id field.

    {!! Form::select('country_id',$countries,null) !!}
    

    But that depends on how your relationship is setup. And how you're saving. Show all the code!