简体   繁体   中英

How to get value from select option without selected the option in Laravel

I have a problem with storing data into my database, because I only know that option value will be storing into database if the option is selected, but how if I want to store all the option that is not selected?

This is my html code

<select multiple id="AllowedCategories" name="allowedPostCategories[]" style="width: 500px; height: 200px; float: left"> </select>

I have a button, that If I click the button it will display a modal. If I choose data in the modal, it will show option, so my html code will change

<select multiple id="AllowedCategories" name="allowedPostCategories[]" style="width: 500px; height: 200px; float: left"> 
   <option value="1">Hello</option> 
   <option value="2">World</option> 
</select>

So, the problem is storing the option value, I have tried to do

return $request->allowedPostCategories;

in my code. But, it return null

Now, I have no idea about how to store the data. I have tried to use

return Input::get('allowedPostCategories');

but, I still got null

If you having allowed category as array,

Then use array_diff to get the unselected values.

For. eg.
$all_categories = $AllowedCategories;
$selected_category = (Input::has('allowedPostCategories')) ? Input::get('allowedPostCategories') : [];
$unselected_Array = array_diff($all_categories,$selected_category);

Hope this helps you.

The answer is:

Set the select option attribute to be true when you submit the form, because option value can only be stored into database if the option is selected

Follow this:-

enter code here
<select multiple id="AllowedCategories" name="allowedPostCategories[]" 
style="width: 500px; height: 200px; float: left"> 
   <option value="1">Hello</option> 
   <option value="2">World</option> 
</select>

I think you can do without jquery also. Firstly, You know all the option values of allowedPostCategories. Now when you post the data in particular controller function. you can do like this controller function

public function  function_name(Request $request){
if($request->isMethod('post')){
    $data = $request->all();
    $allowedcategories = $data['allowedPostCategories'];
    $allcategories = array('1,','2'); // or you can fetch from Database
    $unallowedcategories= array();
    foreach($allcategories as $category){
        if(in_array($category,$allowedcategories)){
            // don't save 
        }else{
            $unallowedcategories[] = $category; //now unallowedcategories you can save in your db
        }
    }
}   
}

Hope it helps!

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