janmoes's avatar

Best way to save single data values to database?

I'm trying to save little pieces of data to the database. For example a phone number, just a value of something i only need one of. I have written some example code to show what i want at the end but not sure if it is the best/only way:

public function index(){
     $customFields = customFields::all();
    
     $fields = [];

     foreach($customFields as $customField){
        $field[$customField['name']] = $customField['value'];
     }
   }
0 likes
2 replies
fylzero's avatar

@janmoes Just a quick tip... your model names should be singular and Capital Case...

public function index(){
     $customFields = CustomField::all();

     foreach($customFields as $customField){
        CustomField::create([
            'name' => $customField['name'],
            'value' => $customField['value']
        ]);
     }
   }
24 likes
janmoes's avatar

Alright, the create function which you've put in the foreach isn't needed, the create function will be in the create function of the controller. The reason i loop them through a new made array is to use the key from the database to use that as the name which contains the value. And because i don't want to loop through the custom fields in the view, i just want to place them mannually.

public function index(){
     $customFields = customField::all();
    
     $fields = [];

     foreach($customFields as $customField){
        $field[$customField['name']] = $customField['value'];
     }
   }

<p>{{$field['location']}}</p>

Please or to participate in this conversation.