Marcello Pato
Marcello Pato

Reputation: 494

Laravel: Querying by id

I am facing a very basic issue but just can't solve.

Two tables: car_models and gear_type. Structured like this:

Model table

Gear table

On the home page, I must show all models and which car with its gear description. So, I am doing:

$modelos = Modelo::all();
foreach ($modelos as $modelo) {
    $cambio = Cambio::where('id', '=', $modelo->cambio_id)->pluck('descricao');
}
// return $cambio;
return view('home', compact('banners', 'modelos', 'cambio'));

But the view shows:

ErrorException (E_ERROR)
Undefined offset: 1 (View: /Users/marcellopato/Sites/primorossiseminovos/resources/views/home.blade.php)
Previous exceptions
Undefined offset: 1 (0)

...and it should show the type of gear within the field indicated in the picture below.

Should show: 5 gear, i.e.

Upvotes: 0

Views: 62

Answers (2)

user10896277
user10896277

Reputation:

Define a relation between two models:

class Modelo extends Model
{
    public function cambio()
    {
        return $this->belongsTo(‘App\Cambio’);
    }
}

Load the relation while query the Modelo:

$modelos = Modelo::with(‘cambio’)->get();

In your view (blade) you could display the gear description as following:

@foreach($modelos as $modelo)
    {{ $modelo->cambio->descricao }}
@endforeach

You could read more about model relation here at docs.

Upvotes: 0

Mihir Bhende
Mihir Bhende

Reputation: 9055

Considering you have foreign key cambio_id inside modelos table, your relationships in model should be :

class Modelo extends Model
{
    public function cambio()
    {
        return $this->belongsTo(‘App\Cambio’);
    }
}

class Cambio extends Model
{
    public function cambio()
    {
        return $this->hasOne(‘App\Modelo’);
    }
}

Then you can do :

$modelos = Modelo::with(‘cambio’)->get();

with() is the eager loading which gets cambio for each modelo instance.

Then you can do :

@foreach($modelos as $modelo)
    {{ $modelo->cambio->descricao }}
@endforeach

Somehow I feel your table structure may be updated and relationship could be reversed, but that depends on the business case also.

Upvotes: 3

Related Questions