jeudi 8 août 2019

Eloquent - How to match data between tables of a single ID

Having multiple tables with data that relates to each other, i'm trying to display that data in a view using Laravel.

I must be confused with how Laravel runs its queries and I need help to sort how to do, what in PHP&SQL would be a left join.

My Asset Model:

public function category(){
        return $this->hasOne(Category::class);
    }

My Category Model:

public function asset()
    {
        return $this->belongsTo(Asset::class);
    }

My Country Model:

public function country()
    {
        return $this->belongsTo(Asset::class);
    }

And my AssetsController:

public function asset($id)
    {

        $asset = Asset::find($id);

        return view('admin.assets.asset')->with('assets', $asset);

    }

And the Router:

Route::get('/admin/assets/asset/{id}', [
        'uses' => 'AssetsController@asset',
        'as' => 'assets.asset'
        //Show the Asset
    ]);

And the View:

<p><strong>Price:</strong> €</p>
<p><strong>Description:</strong></p>
<p><strong>Country:</strong></p>
<p><strong>Category:</strong></p>

So in the 'asset.blade.php' I get the id from a previous index.blade.php that has a list of all the assets. I want to get via the ID, an asset page that displays the category name and the country name, instead of the ID that belongs to the Asset table.

So it should echo something like $assets->country->country_name and $assets->category->name

dd($asset);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire