How have you setup the Team and Player relationships? Can we see you code please?
Hi,
Yeah here is my Team model:
public function getLogo($league='nhl'){
$filename = str_replace(' ', '', $this->team_name);
$filename = $filename. ".png";
$path = '/assets/images/logos/' .$league. '/' .$filename;
$image = HTML::image($path, $alt=$this->team_name, $attributes=array('width'=>'40px','height'=>'40px'));
return $image;
}
public function players()
{
return $this->hasMany('Player','team');
}
Player model:
public function team()
{
return $this->belongsTo('Team','team');
}
And my call:
$player->team()->getLogo();
Hi eriktisme,
I get the following error: Call to a member function getLogo() on a non-object
Could it be because there is a field name called team?
This means that there is no result so either there's no team for this player or no image found.
Hi,
Pretty sure there is a result... I just ran a test query for a player that is sure to have a team...
So, eriktisme wrote right, but your problem seems to be on relationship or database schema.
To get it work you should have database schema like that:
Players = id, team_id, ...rest of fields
Teams = id, ...rest of fields
Team Model
protected $table = 'Team'; //only if your table is not in plural
public function players(){
return $this->hasMany('Player'); //this assume that your Player model has team_id field
}
Player Model
public function team(){
return $this->belongsTo('Team'); //this assume that your Player model has team_id field
}
Now, just call things using: Team logo from $player = $player->team->getLogo()
Note: use $player->team->attribue and NOT $player->team()->attribute Array with all players of team = $team->players
Hi the relationship works, as a matter of fact, when I just pritn this:
$player->team it shows the team full details... When I do this: $player->team['team_name']
It works just fine... But now when I do $player->team->team_name...
Why is that?
Does the $player table have a field called 'team' ? If so, either rename that field or simply rename the relationship.
asivaneswaran said:
Hi eriktisme,
I get the following error: Call to a member function getLogo() on a non-object
Could it be because there is a field name called team?
Yes, exactly. This is your problem here. If you have property with the same name as a relation, then you can't use dynamic properties.
Rename either relation, or (better) column to team_id
.
Also you can get the relation anyway:
$player->load('team');
$player->getRelation('team');
// it will return exactly the same what you would expect from:
$player->team;
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community