return select "related table" in the Format

Asked

Viewed 39 times

0

Hello my application was developed in Modular and as a complement I am using some components of Vuejs.

Let’s get to the problem, I have a client table doing relationship with country. In the same index.Blade view of clients I open a modal to create, edit and view the client. The point is that to create the client it presents the select with the countries registered, but when editing or viewing it does not return the countries. Let’s go to the code:

Clientescontroller: (In it I call also the model parents)

public function index()
{
    $listaClientes = Cliente::select('id', 'nome', 'tva', 'pais_id', 'cp', 'cidade', 'endereco')->paginate(10);

    $pais = Pais::all();

    return view('app.clientes.index',compact('listaClientes', 'pais'));
}

Model Pais:

{
use SoftDeletes;

protected $table = 'paises';
protected $fillable = ['id', 'nome'];

protected $dates = ['deleted_at'];

Customer model:

use SoftDeletes;

protected $table = 'clientes';
protected $fillable = ['nome', 'tva','pais_id', 'cp', 'cidade', 'endereco'];

protected $dates = ['deleted_at'];

public function pais() {
    return $this->belongsToMany('App\Pais', 'pais_id', 'nome');

Add modal select:

<select name="pais_id" class="form-control">
   @foreach ($pais as $pais)
      <option value="{{ $pais->id }}">{{ $pais->nome }}</option>
   @endforeach
</select>

Select of the edit modal:

<select name="pais_id" class="form-control">
   @foreach ($pais as $pais)
      <option value="{{ $pais->id }}">{{ $pais->nome }}</option>
   @endforeach
</select>

My add and edit forms are in the same file and open the modal...

Thank you for your attention, if there’s anything else I need to send...

  • Put the dump exit($pais); or dd($pais); Tip, change $pais = Pais:::all(); to $paises = Pais:::all(); so that in the foreach it is not so confusing :)

  • Opa, thanks Marcos. I got here with the help of another boy, exactly as you indicated. Valeuuu

1 answer

0


In both foreach, you used the item name equal to the Collection name $pais => $pais, this is a possible source of the bug. To fix this I suggest that in the controller, replace the variable $pais for $paises, as in the example below:

public function index()
{
    $listaClientes = Cliente::select('id', 'nome', 'tva', 'pais_id', 'cp', 'cidade', 'endereco')->paginate(10);

    $paises = Pais::all();

    return view('app.clientes.index',compact('listaClientes', 'paises'));
}

And in the view, change @foreach($pais as $pais) for @foreach($paises as $pais)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.