简体   繁体   中英

Avoiding trigering foreign key constraint when dropdown is not selected

I have a select dropdown using laravel form helper like so:

{!! Form::label('job_id', 'Job Titlle', ['class' => ' control-label']) !!}
{!! Form::select('job_id', $jobs, null, ['class' => 'form-control', 'placeholder' => 'Select']) !!}

The problem is this causes a foreign key constraint when I try to update the model . I think an empty string is passed and I don't lnow how to stop that from happening.

please help Thanks!

1) Validate the data before sending it off to the database; something like this in your controller will do the trick:

class JobController extends Controller
{
    public function store(Request $request)
    {

        $this->validate($request, [
             'job_id' => 'required'
        ]);

        // Store in the database because data is valid
    }
}

2) If job_id is not really required, you can avoid the foreign key contraint failure by specifying the column as nullable

在Database表中,使列为null

ALTER mytable MODIFY mycolumn varchar(255) null;

This did the trick for me.

if(isset($request['fk_id']) && empty($request['fk_id'])) {
            $request['fk_id'] = null;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM