I'm pretty new to Laravel and working on a system with multiple levels of relationships between database tables.
Briefly, I have a situation involving three database tables - Tournaments, which can have multiple Attendees, and each Attendee's details are stored in a "meta" table, which stores data by key - value (such as their name, address, email, telephone etc).
What I need to do is for a tournament, display a list of attendees using values from the meta table for each one.
Here's where I'm at so far, I have this working, but I want to refactor the code to be more reusable and efficient, plus as I'm new to Laravel I'd like to learn more too.
database tables
Schema::create('tournaments', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
});
Schema::create('attendees', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('tournament_id')->unsigned();
$table->index('tournament_id');
});
Schema::create('attendees_meta', function (Blueprint $table) {
$table->increments('id');
$table->string('key', 50);
$table->text('value');
$table->integer('attendee_id')->unsigned();
$table->index('key');
$table->index('attendee_id');
});
There are more fields to the above tables which aren't relevant here. Next my Models:
Tournament Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tournament extends Model
{
/**
* The attendees relationship
*/
public function attendees()
{
return $this->hasMany('App\Attendees');
}
}
Attendees Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Attendees extends Model
{
/**
* The tournament relationship
*/
public function tournament() {
return $this->belongsTo('App\Tournament');
}
}
AttendeesMeta Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class AttendeesMeta extends Model
{
/**
* The table
*
* @var string
*/
protected $table = 'attendees_meta';
}
I know there should be a one to many relationship between the Attendees and AttendeesMeta, but I couldn't get this to work with that relationship in place.
In my controller I have this:
public function dashboard(Tournament $tournament) {
$data['tournament'] = $tournament;
$attendees = Attendees::where('tournament_id', $tournament->id)->get()->toArray();
foreach ( $attendees AS $attendee ) {
$attendee['meta'] = AttendeesMeta::where('attendee_id', $attendee['id'])->get()->keyBy('key')->toArray();
$data['attendees'][] = $attendee;
}
return view('manager.dashboard', $data);
}
This allows me in my view to do the following:
@foreach ( $attendees AS $attendee )
{{ $attendee['meta']['name']['value'] }}
{{ $attendee['meta']['email']['value'] }}
@endforeach
I'm sure there's a better way to produce these results and construct these relationships?