Laravel - Models and Relations

Cheat-sheet

  • Use dump or dd in Laravel to get extended information
  • dd($user);

Model

  • Connection to 'something' you want to use within the application
  • Stored often in database, file, cloud-solution
  • Found directly in the app/ folder
    • app/User.php

Model writing

  • Always singular (while database always plural)
    • The object User is always one user, the database table can hold many users
  • CamelCase written
    • User -> users table
    • UserGroup -> user_group table

Fetching data from a model

  • $users = User::all();
    • Returns an array with objects of all users
  • $users = User::where('created_at', '>', '2017-01-01')->get();
    • Returns an array with objects of all the users that where created after the date

Fetching just one object

  • $user = User::find(1);
    • Returns an object with the user with ID 1
  • $user = User::findOrFail(1)
    • Returns an object with  the user with ID 1 or breaks the application
    •  
  • $user = User::where('email_address', '=', 'michiel@competa.com')->first();
    • returns an object of the first user that matches

Read more on Laravel.com

What is a relation

  • A connection between two or more models
  • Often connected with a foreign key in database

Relation examples

  • Rubric -> Peer
    • table peers has rubric_id
  • Round -> Group
    • table group has group_id
  • Group -> Round
    • table group has round_id

More complex relations

  • User -> UserGroup -> Group
    • user_group has user_id and group_id
  • User -> UserRole -> Roles
    • user_roles has user_id and role_id
  • Group -> Group
    • groups has group_id (can be null)

Read more on Laravel.com

Relations in a Laravel model

  • hasOne -> one to one relation
  • hasMany -> one to many relation
  • belongsTo -> one or many to one relation
  • belongsToMany -> many to many relation

Working with a relation

//From the Round.php model
function group () {
  return $this->belongsTo('App\Group');
}

//From the RoundController.php
//Get all the rounds (this will return an array with objects)
$rounds = Round::all();

//Loop thru the rounds
foreach ($rounds AS $round) {
  //get the group relation, and show the group name
  echo $round->group->name;
}

/*
* Mind you a relation with hasOne/hasMany/belongsTo/belongsToMany are ATTRIBUTES of the model
* it is not a function, so do not use () at the end (it will not show a thing)
*/

Working with a relation

//From the Round.php model
public function peers() {
  return $this->hasMany('App\Peer');
}

//From the RoundController.php
//Get all the rounds (this will return an array with objects)
$rounds = Round::all();

//Loop thru the rounds
foreach ($rounds AS $round) {
  //get the group relation, and show the group name
  echo $round->peers->id
}

^^^ This will not work...  

Working with a relation

//From the Round.php model
public function peers() {
  return $this->hasMany('App\Peer');
}

//From the RoundController.php
//Get all the rounds (this will return an array with objects)
$rounds = Round::all();

//Loop thru the rounds
foreach ($rounds AS $round) {
  //get the group relation, and show the group name
  foreach ($round->peers AS $peer) {
    echo $peer->id
  }
}

Alternative field-names

//From the Peer model
public function reviewer() {
  return $this->belongsTo('App\User', 'reviewer_id');
}                                     ^^^^^^^^^^^^^ Alternative 

//get all the peers
$peers = Peer::all();

//Loop thru the rounds
foreach ($peers AS $peer) {
  $peer->reviewer->name; // Gets the user name from the reviewer    
}

Read more on Laravel.com

Using relations to filter data

  • Rubrics groups have students
  • Use relation Group->users and select only the students

Getting the students

//From the Group.php model
public function parent() {
  return $this->belongsTo('App\Group', 'group_id');
}
public function users() {
  return $this->belongsToMany('App\User', 'user_groups', 'group_id', 'user_id');
}

public function students() {
  return $this->users()->whereHas('roles', function ($q) {
    $q->Where('ident', '=', 'student');
  })->get();
}

//From the PeerController.php
public function create(Group $group) {
    if ($group->parent) {
        $parent = Group::where('id', $group->group_id)->first();
        $users = $parent->teachers();
    }

    if (!$group->parent) {
        $users = $group->teachers();
    }

    $rubrics = Rubric::all();

    return view('peer.create', compact('rubrics', 'users', 'group'));
}

Read more on Laravel.com

What's next?

  • Reading :-)
  • Read up on scopes
  • Read up on functions

Read more on Laravel.com

Laravel - Models & Relations

By CodePamoja

Laravel - Models & Relations

Small presentation about Laravel models and their relations. Based on the Rubrics project

  • 32