Support the ongoing development of Laravel.io →
Database Eloquent Views

Hi all,

i am new to laravel and have a fictional Project to learn:

I have two Models: Sports and Trainers

Sport Model:

class Sport extends \Eloquent {

	// Add your validation rules here
	public static $rules = [
		// 'title' => 'required'
	];

	// Don't forget to fill this array
	protected $fillable = [ "sports_nicename"];

	public function trainers() {
		return $this->hasmany('Trainer', 'sport_id');
	}

}

Trainer Model

class Trainer extends \Eloquent {
	


	// Add your validation rules here
	public static $rules = [
		'trainer_name' => 'required|unique:trainers'
	];

	public static $updaterules = [
		'trainer_name' => 'required'
	];

	// Don't forget to fill this array
	protected $fillable = ["trainer_name", "trainer_nationality", "trainer_avatar", "trainer_birthday"];

	public function sport() {
		return $this->belongsTo('Sport', 'sport_id'); // this matches the Eloquent model
	}

	

}

My controllers are pretty much normal:

TrainerController.php (index part)

public function index()
	{
		$trainers = Trainer::all();

		return View::make('trainers.index', compact('trainers'));
	}

and SportsController.php (index part)

public function index()
	{
		$sports = Sport::all();

		return View::make('sports.index', compact('sports'));
	}

On my index View for the trainers i have something like this:

@foreach ($trainers as $trainer)
 <li>{{ $trainer->trainer_name}} 
<li>{{ $trainer->sport->sport_nicename }} 
@endforeach

My problem lies here: {{ $trainer->sport->sport_nicename }} It returns NULL, but {{ var_dump( $trainer->sport) }} returns the whole Object.

Any idea how could i access the field sport_nicename for every $trainer?

Thanks and greets

Last updated 3 years ago.
0

I guess it's a typo... Try "sports_nicename" (you forgot an "s", see your fillable property above)

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.