简体   繁体   中英

Laravel: Add data to the $request->all()

I wan to add the sector id to the request but when I submit the data nothing store on it. Here is my code

public function store(QuestionRequest $request)
    {
        $data = $request->all();
        Question::create($data);
        $sectors =  Sector::lists('id');
        foreach($sectors as $sector){
            CustomizeQuestion::create(array_add($request->all(), 'sector_id', $sector));
        }

        flash()->success('New question has been added.');
        return redirect('questions');
    }

I have tried this code also but it is the same :

public function store(QuestionRequest $request)
    {
        $data = $request->all();
        Question::create($data);
        $sectors =  Sector::lists('id');
        foreach($sectors as $sector){
            $data['sector_id'] = $sector;
            CustomizeQuestion::create($data);
        }

        flash()->success('New question has been added.');
        return redirect('questions');
    }

If you only want to add one 'id' to your request as you said, you can simply do this before creating anything :

$data = $request->all();
$data['sector_id'] = whatever you want;
Question::create($data);

Or like the second way you showed.

If this approach doesn't work verify if you have your properties specified in the model's fillable array and if you are using the correct property name as you specified in your migration.

First of all check your CustomizeQuestion model. sector_id should be in $fillable array. Example:

protected $fillable = [
    'sector_id',
    'more',
    'and_more'
];

And if your form return only one id to store method no need to use foreach or list your id . Simply do this:

$data['sector_id'] = $request['id'];
CustomizeQuestion::create($data);

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