Jhonatan Mendes
Jhonatan Mendes

Reputation: 99

Laravel: Select Option from different table

I was studying laravel the last few days, and I was wondering if I could do a foreach on a select tag that get record from a specific table

so in my controller I have this, basically it's a validation that returns the record if it exists

public function create(Request $request)
    {
        //
        $cpf = $request->input('cpf');

        $cooperado = \DB::table('cooperados')   // query builder, busca o registro de acordo com cpf
            ->select('id', 'nome', 'cpf')
            ->where('cpf', '=', $cpf)
            ->first();

        //$cooperado = Cooperados::find($id);
        //return view('cadastro.create', compact('cooperado'));

        if(count($cooperado) == 0){

            return redirect('validar')->with('success', 'CPF incorreto ou não registrado');
            //return view('cadastro.create', compact('cooperado'));

        } else {

            //return redirect('validar')->with('success', 'CPF incorreto ou não registrado');
            return view('cadastro.create', compact('cooperado'));

        }

    }

and thats how my create view looks like

<form action="{{ route('cadastro.store') }}" method="POST">
                    @csrf
                    <div class="row">
                        <div class="col">
                        <label for="cooperado">Cooperado</label>
                        <input type="text" class="form-control" value="{{ $cooperado->nome }}" readonly>
                        </div>
                        <div class="col">
                        <label for="cpf">CPF</label>
                        <input type="text" class="form-control" value="{{ $cooperado->cpf }}" readonly>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="dependente">Dependente</label>
                        <input type="text" class="form-control" id="dependente" placeholder="Nome do estudante">
                    </div>
                    <div class="form-group">
                        <label for="extracurricular">Extracurricular</label>
                        <select class="form-control" id="extracurricular">
                        <option>Futsal</option>
                        <option>Volei</option>
                        <option>Futebol</option>
                        <option>Internet</option>
                        <option>Radio</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="dependente">Série</label>
                        <input type="text" class="form-control" id="dependente" placeholder="Exemplo: 3 Serie D">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">
                                Cadastrar
                        </button>
                    </div>
                    </form>

as you can see i have a select tag on my form, and i would like to use foreach that select record from a different table, i know that is not cool make queries in my view, so how can i do this? (this form is like a student registration, and the select tag its where the student choice his course)

Upvotes: 1

Views: 2985

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

This is pretty common, and you're correct; don't add query logic to your view. Since a Controller is returning that view, do the query in the controller and pass it to the view. Say you have a table courses that contains a record for "Futsal", "Volei", etc. Adjust your controller like so:

$cpf = $request->input('cpf');

$cooperado = \DB::table('cooperados')
->select('id', 'nome', 'cpf')
->where('cpf', '=', $cpf)
->first();

$courses = Course::orderBy('name')->get();
// Note: use DB::table('courses') if you don't have a `Course` model, but models are preferred

return view('cadastro.create', compact('cooperado', 'courses'));

Then, in your view, use a foreach over the values of $courses:

<select class="form-control" id="extracurricular" name="course">
  @foreach($courses AS $course)
  <option value="{{ $course->id }}">{{ $course->name }}</option>
  @endforeach
</select>

If done correctly, you should have multiple <option> elements in your <select> matching the courses in your database.

Note: added name="course" to your <select>, value can be retrieved in the Controller handling the POST request via $request->input("course"), and will be the id of the course selected.

Upvotes: 1

Related Questions