Home > Blockchain >  Check dynamic variable of an array contains value or not in php
Check dynamic variable of an array contains value or not in php

Time:06-15

This is my basic form to create contacts in create.vue --


    <div >
     <label >Name</label>
     <div>
       <input type="text"  placeholder="Enter Name" v-model="form.name" required>
     </div>
    </div>
    <div >
     <label >Contact Id</label>
     <div>
       <input type="text"  placeholder="Enter Contact Id" v- 
        model="form.contact_id" required>
     </div>
    </div>   

  

then I am giving the option to add address in the same form but which is not required. but if USER wants, while creating contact , user can add multiple addresses as well.


    <div  v-for="(item, k) in form.addresses" :key="k" >
      <label for="exampleFormControlInput1" >Street 1:</label>
      <div >
         <input  type="text" v-model="item.street1" name="street1" 
          placeholder="Enter Street 1">  
      </div>
      <div >
         <label for="exampleFormControlInput1" >State</label>
         <select   v-model="item.state_id" name="state_id">
            <option value="">Choose State</option>
            <option value="1">Manitoba</option>
            <option value="2">Winnipeg</option>
            <option value="3">Punjab</option>
            <option value="4">Other</option>
         </select>   
       </div>
       <div >
         <label for="exampleFormControlInput1" >Country</label>
         <select   v-model="item.country_id" name="country_id">
            <option value="">Choose Country</option>
            <option value="1">Canada</option>
            <option value="2">U.S</option>
            <option value="3">India</option>
            <option value="4">Other</option>
         </select>   
        </div>
        <div >
          <button  type="button" 
           @click="removeAddress(k)">Remove</button>  
        </div>
     </div>
     <div >
       <div >
         <input  type="button" value="Add Another Address" 
         @click="addAddress()"> 
       </div>
     </div>

But whenever i am storing the data in database, it should be stored if only name has been given .

In the controller, my data is being fetched like this if i use return $request->all()-- {"name":"y","contact_id":"y","addresses":"[{"street1":"y","state_id":"1","country_id":"1"}]"}

Below is my controller code --


   public function store(Request $request)
       {
           //return $request->all();
           $contact = Contacts::create([
               'name' => $request->name,
               'company_id' => Auth::user()->company_id,
           ]);
           $addresses= json_decode($request->addresses, true);
           //return $addresses;
           //[{"street1":"","state_id":"","country_id":""}]
           if (! empty($addresses)) {
            foreach($addresses as $ad) {
                   $address = new Address;
                   $address->contact_id = $contact->id;
                   $address->street1 = $ad['street1'];
                   $address->state_id = $ad['state_id'];
                   $address->country_id = $ad['country_id'];
                   $address->save();
               } 
      }

how to check if variable values of street, state and country is null, it should not store data. It is returning me error

Invalid datetime format: 1366 Incorrect integer value: '' for column clientchief_db.addresses.state_id at row 1 (SQL: insert into addresses (contact_id, street1, state_id, country_id, updated_at, created_at) values (14, , , , 2022-06-14 19:26:49, 2022-06-14 19:26:49))"

CodePudding user response:

You should validate your request:

$request->validate([
    'addresses' => ['required', 'array'],
    'addresses.*.street1' => ['required', 'string'],
    'addresses.*.state_id' => ['required', 'numeric'],
    'addresses.*.country_id' => ['required', 'numeric'],
]);

CodePudding user response:

If I understand it right

  • User can fill up just name & submit the form - data should be persisted in the database
  • User can fill up multiple address, but if user doesn't fill up complete details (street, state & country should be filled) for the address it should not be persisted in the database

One approach would be to

  • validate the address data, ONLY if user added address to the form
  • and return validation error if street1, state_id or country_id is null
public function store(Request $request)
{
    //return $request->all();

    $validated = $request->validate([
        'name' => ['required', 'string'],
        'addresses' => ['sometimes', 'array'],
        'addresses.*.street1' => ['sometimes', 'required', 'string'],
        'addresses.*.state_id' => ['sometimes', 'required', 'numeric'],
        'addresses.*.country_id' => ['sometimes', 'required', 'numeric'],
    ]);

    //The above will pass validation if name is filled as non empty string & addresses is not present in the request data
    //But if the addresses is present in the request, it will fail if either of  street1, state_id or country_id is null

    $contact = Contacts::create([
        'name' => $request->name,
        'company_id' => Auth::user()->company_id,
    ]);

    $addresses= json_decode($request->addresses, true);
    //return $addresses;
    //[{"street1":"","state_id":"","country_id":""}]
    if (! empty($addresses)) {
        foreach($addresses as $ad) {
            $address = new Address;
            $address->contact_id = $contact->id;
            $address->street1 = $ad['street1'];
            $address->state_id = $ad['state_id'];
            $address->country_id = $ad['country_id'];
            $address->save();
        } 
    }

    //return response
}

Laravel Docs - Validation - Validating When Present

  • Related