MattB
4 months ago
631
3
Laravel

one to many relation not working

Posted 4 months ago by MattB

I have a table of games, games companies and consoles. I am trying to output games to JSON using the API in Laravel and connecting the tables in a way that given the company ID and console ID in the games table, I can cross-reference the company/console name from the other table to fill in the name.

Game Model:

class Game extends Model
{
    public function company()
    {
        return $this->belongsTo('App\Company', 'company_id');
    }

    public function console()
    {
        return $this->hasOne('App\Console', 'console_id');
    }
}

company Model (console is similar):

class Company extends Model
{
    public function game()
    {
        return $this->hasMany('App\Game');
    }
}

I have this in my controller so far:

 public function show($id)
    {
        $showGame= Game::where('id', $id)->first();        
        return response()->json([
            'showGame' => $showGame
        ]);
    }

This will output this as JSON but I wanted company and console to have the names rather than numbers:

{
    "showGame": {
        "id": 2,
        "company_id": 2,
        "console_id": 1,
        "title": "Sonic",
        "price": £10,
	"inStock": "yes"          
    }
}

I tried the following which gives the company name just fine but then won't display the rest of the data (It just stops at company_id):

 public function show($id)
    {
        $showGame= Game::find($id)->company->where('id', $id)->first();        
        return response()->json([
            'showGame' => $showGame
        ]);
    }

Please sign in or create an account to participate in this conversation.