Oscar
Oscar

Reputation: 139

How to send a query in a variable using laravel?

I have this function to register my users

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'apellido' => ['required', 'string', 'max:255'],
        'idop' => ['required', 'string', 'max:6', 'unique:users'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'cedula' => ['required', 'int'],
        'fecha_nacimiento' => ['required', 'date'],
        'fecha_ingreso' => ['required', 'date'],
        'extension' => ['required', 'int'],
        'movil' => ['required', 'int'],
        'tel_hab' => ['required', 'int']
    ]);

}

I would like to send this query in a variable ($generos) to make a select

$generos = DB::table('tbl_lista_generos')
            ->select('id','genero')
            ->get();

How could I do that?

Upvotes: 1

Views: 60

Answers (2)

Sehdev
Sehdev

Reputation: 5662

You can pass the variable from controller to view using below ways:

Way1

$generos = DB::table('tbl_lista_generos')
            ->select('id','genero')
            ->get();
return view("index", compact("generos "));

Way2

 $generos = DB::table('tbl_lista_generos')
                ->select('id','genero')
                ->get();
 return view("index", ["generos" => $generos]);

Way3

 $generos = DB::table('tbl_lista_generos')
                ->select('id','genero')
                ->get();
 return view("index")->with(["generos" => $generos]);

On your view file::

 <select name="genero">
  <option value=''>select</option>
   @foreach ($generos as $genero)
     <option value="{{ $genero->id }}">{{ $genero->name}}</option>
   @enforeach
</select>

Upvotes: 2

helderneves91
helderneves91

Reputation: 975

by the comments, you want to send the result of the query to the view. So,

In your controller function do:

return view('generos.index', [
      'generos' => DB::table('tbl_lista_generos')->select('id','genero')->get()
]);

In the view:

<select class='' name='select_form_generos'>
<option value=''>select genero</option>
@foreach ($generos as $genero)
     <option value='{{ $genero->id }}'>{{ $genero->genero}}</option>
@enforeach
</select>

Hope it helped!

Upvotes: 0

Related Questions