Laravel - Creating select with Form::select + Model::lists

Asked

Viewed 6,290 times

2

I’m trying to create a select with the following code:

My controller is like this:

public function create(){
    $marcas = Marca::lists('descricao', 'id')->toArray();
    return view('sistema.modelos.create', ['marcas'=>$marcas]);
}

My view is like this:

{!! Form::open(['route'=>'sistema.modelos.store']) !!}
{!! Form::select('marca_id', $marcas ) !!}
{!! Form::close() !!}

You’re making the following mistake:

Trying to get property of non-objec

Has anyone ever been through it? You know how to do it?

editing---

I already did that:

$marcas = Marca::all(['id', 'descricao']);
return view('sistema.modelos.create', compact('marcas',$marcas));

according to the link: https://stackoverflow.com/questions/29508297/laravel-5-how-to-populate-select-box-from-database-with-id-value-and-name-value

In this case select is even rendered, but stays like this:

<select name="marca_id"><option value="0">{id : 1 , descricao : NOME}</option></select>
  • This Pact has nothing to do. You don’t need to pass the variable in it.

1 answer

3


You should initialize select with an array and not Collection, try changing from

$marcas = Marca::lists('descricao', 'id');

for

$marcas = Marca::lists('descricao', 'id')->toArray();

or in Laravel 5.2

$marcas = Marca::pluck('descricao', 'id');

If you want a neutral value for select, try using the attribute placeholder or give a append before transforming Collection into an array.

  • Keeps making the same mistake.

  • Try changing from ->all(); to ->toArray();.

  • Keeps making the same mistake.

  • Like this: $marks = Tag::all(['id', 'Description']); Return view('system.modelos.create', Compact('marks',$marks)); ' mounts the select but draws the whole object

  • In fact with the answer I gave you is to work with 100% certainty, we can investigate the other parts of your code?

  • I put more information... see please

  • Even with the Tag::Pluck('Description', 'id') did not work, it still gives the same error:

  • Can somehow show me the full error log?

  • It’s right the way I’m passing the '$tags' variable to the view?

  • The error was in my own code elsewhere. Rafael Berro’s solution worked perfectly!

  • How best to create empty option ?

  • You can append Collection before using toArray(), or you can place the placeholder attribute in the html field.

Show 8 more comments

Browser other questions tagged

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