Search code examples
phpmysqllaraveleloquentlaravel-blade

Laravel @foreach - How do I display the for each value that belong to a relationship model


Morning,

I am trying to return on an index.blade within Laravel 7

My site is set with a link to the Leagues = leagues.index blade (displays each league = at present 2)

From within leagues.index I select "go to League" = leagues.show blade (displays chosen league's menus and details)

Within the leagues.show blade there is a link to teams = teams.index blade (this at the moment displays all 64 teams from the two leagues)

What I would like to show within the teams.index blade

@foreach team that belongs to the specific league (total of 32 teams).

I have included two images of the table structures.

(1) leagues table structure

(2) my teaminfo structure.

The leagueId (1) and (2) is how I would like to define each league

I would like to return within the teams index.blade is

*league 1 and its 32 relevant teams displayed for the specific leagueId (1) and not display leagueId (2) teams

*league 2 and its 32 relevant teams displaying for the specific leagueId (2) and not display leagueId (1) teams

The code used at present is

LeaguesController

class LeaguesController extends Controller{

public function index()
{

    $leagues = League::all();
    return view('leagues.index', compact('leagues'));

}

   public function show($ID)
{
    $league = League::find($ID);
    return view('leagues.show')->with('league', $league);

}

   public function team()
{
    return this;hasMany(Team::class);

}}

Teams Controller

class TeamsController extends Controller{

public function index()
{
    $teams = Team::all();
    return view('teams.index', compact('teams'));
}

   public function show($ID)
{
    $team = Team::find($ID);
    return view('teams.show')->with('team', $team);

}
    public function leagues()
{

    return $this;belongsTo(League::class);
}}

League Model

class League extends Model{
use SoftDeletes;
const default = 1;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'leagues';

//public $primaryKey = 'shortName';

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */
public $timestamps = true;

/**
 * The attributes that are not mass assignable.
 *
 * @var array
 */
protected $guarded = [
    'id',
];

/**
 * The attributes that are hidden.
 *
 * @var array
 */
protected $hidden = [];

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = [
    'created_at',
    'updated_at',
    'deleted_at',
];

/**
 * Fillable fields for a Profile.
 *
 * @var array
 */
protected $fillable = [
    'name',
    'shortName',
    'exportId',
    'platform',
    'taggable_id',
    'taggable_type',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'id'            => 'integer',
    'name'          => 'string',
    'shortName'     => 'string',
    'exportId'      => 'string',
    'platform'      => 'string',
    'taggable_id'   => 'integer',
    'taggable_type' => 'string',
];

/**
 * Get a validator for an incoming registration request.
 *
 * @param array $data
 *
 * @return array
 */
public static function rules($id = 0, $merge = [])
{
    return array_merge(
        [
            'name'   => 'required|min:3|max:50|unique:leagues,name'.($id ? ",$id" : ''),
            'shortName'   => 'required|min:3|max:10|unique:leagues,shortName'.($id ? ",$id" : ''),
            'exportId'  => 'max:5',
            'platform' => 'required',
        ],
        $merge
    );
}

/**
 * Get the profiles for the league.
 */
public function profile()
{
    return $this->hasMany('App\Models\Profile');
}
public function team()
{
    return $this->hasMany('App\Models\Team');
}}

Team Model

class Team extends Model{

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'teaminfo';
public $primaryKey = 'displayName';
/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */
public $timestamps = false;

/**
 * The attributes that are not mass assignable.
 *
 * @var array
 */
protected $guarded = [
    'leagueId',
];

/**
 * The attributes that are hidden.
 *
 * @var array
 */
protected $hidden = [];


/**
 * Fillable fields for a Profile.
 *
 * @var array
 */
protected $fillable = [
    'teamId',
    'abbrName',
    'cityName',
    'displayName',
    'divName',
    'offScheme',
    'defScheme',
    'ovrRating',
    'injuryCount',
    'primaryColor',
    'secondaryColor',
    'userName',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'teamId'            => 'integer',
    'abbrName'          => 'string',
    'cityName'          => 'string',
    'displayName'       => 'string',
    'divName'           => 'string',
    'offScheme'         => 'string',
    'defScheme'         => 'string',
    'ovrRating'         => 'string',
    'injuryCount'       => 'string',
    'primaryColor'      => 'string',
    'secondaryColor'    => 'string',
    'userName'          => 'string',
];

    /**
 * Get the profiles for the league.
 */
public function profile()
{
    return $this->hasMany('App\Models\Profile');
}

    public function team()
{
    return $this->belongsTo('App\Models\League');
}}

Any assistance would be greatly appreciated, and If you require more info and/or visual please ask..

leagues MySQL table

teaminfo MySQL table


Solution

  • In your route:

    Route::get("/league/{league}/teams);
    

    In your controller:

    public function index(League $league) {
        $teams = $league->team;
        return view('teams.index', compact('teams'));
    }
    

    Now, if you access /league/1/teams, laravel will find the league with id 1 and retrive all the teams belongs to that league. And yes, it works for /league/2/teams, whatevery you put it there, laravel will treat it as the id of leagues, if laravel can't find it, a 404 page will be shown.