Skip to content
Advertisement

dropdown is populating empty list in laravel 6

Laravel Version 6. PHP 7.4.

I simply wants to populate my dropdown values form database table. Initially, It was returning error “variable undefined” but when I enclosed my code into if condition, my error was gone but drop-down list is empty.

Please suggest where I’ m stuck.

Route.php

Route::get('products/qrcodes/basic','niceActionController@getMake');

Controller

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppNiceAction;
use AppNiceActionLogged;

public function getMake()
{
$records = DB::table('users')->get();
return view('products.qrcodes.basic', ['records' => $records]);
}

View

<form>
   <select  required>
     @if ((empty($records)))
        Whoops! Something went wrong
     @else
     @foreach ($records as $item)
     <option value="{{ $item->id }}">{{ $item->name }}</option>
     @endforeach
     @endif
   </select>
</form>

I also tried “dd($records);” but nothing happens.

Advertisement

Answer

First Make sure that your table have data. And then change your controller and view like this.

Controller Code

<?php

   namespace AppHttpControllers;

   use DB;
   use IlluminateHttpRequest;
   use AppNiceAction;
   use AppNiceActionLogged;

   public function getMake() {
       $records = DB::table('users')->get()->toArray();
       return view('products.qrcodes.basic', compact('records'));
   }

View Code:

<form>
    <select required>
        @if(empty($records))
            Whoops! Something went wrong
        @else
            @foreach ($records as $key => $item)
                <option value="{{ $item['id'] }}">{{ $item['name'] }}</option>
            @endforeach
        @endif
    </select>
</form>

I hope it will help you 🙂

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement