I have an input looks like this.

{!! Form::text('inventory[0][amount]', null, ['class'=>'form-control']) !!}
{!! Form::text('inventory[0][expiry_date]', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control']) !!}

print_r( $_POST ) results

[inventory] => Array ( [0] => Array ( [amount] => 66 [expiry_date] => 2019/05/20 ) )

I am trying to check if the amount and the expiry_date are not null

if ( $input['inventory[0][amount]'] and $input['inventory[0][expiry_date]'] != null )

Got

Undefined index: inventory[0][amount]

4 Answers

3
Always Sunny On Best Solutions

Try this way with !empty(),

if (!empty($_POST['inventory'][0]['amount']) && !empty($_POST['inventory'][0]['expiry_date']))
{ 
    //You code goes here
}
0
Rakesh Kumar Jakhar On

You are not using the array key properly, Replace your code with

$arr = array(
 'inventory' => Array (
  0 => Array (
     'amount' => 66,
     'expiry_date' => '2019/05/20'
  ) 
 )
);

if($arr['inventory'][0]['amount'] and $arr['inventory'][0]['expiry_date'] != ''){
2
Jack On

You can use dot notation and $request->filled($keys) to achieve this...

$request->filled(['inventory.0.amount', 'inventory.0.expiry_date'])

Will return true if amount and expiry_date are present and not empty.

For example, assuming you want to perform the check in your controller...

use Illuminate\Http\Request;

// ...

class YourController extends Controller
{
    public function store(Request $request)
    {
        if ($request->filled(['inventory.0.amount', 'inventory.0.expiry_date'])) {
            // Both amount and expiry_date are present and not empty...
            // You can also use the request() helper if you don't want inject the Request class...
        }
    }
}

I'd also suggest that unless you have multiple inventory items, i.e inventory[n]['amount'] - you change the input name to inventory[amount].

This means that you can do the following:

$request->filled('inventory.amount') // or (isset($input['inventory']['amount']) && ! empty($input['inventory']['amount']))

Edit

filled() was introduced in 5.5, it should be replaced with has() in 5.4.

0
Danyal Sandeelo On

There is no key with name 'inventory[0][amount]' in this array so it would be checked like this:

if(array_key_exists('inventory',$input) &&  
     array_key_exists(0,$input['inventory'])  &&  
     array_key_exists('amount',$input['inventory'][0])  && 
       !empty($input['inventory'][0]['amount'])
//add for expiry too
 ){

}