Eloquent Relations in Laravel 5

It is a sample from Chapter Twelve of the book : Laravel 5 : Learn Easy: Computer Programming For Everybody and
Laravel 5 : Learn Easy: Computer Programming For Everybody
Now we have learned to create tables through Migration and Tinker. We can also use Eloquent ORM to do the same. We also have learned to update or edit our database records. And I hope by this time you have already been able to build up a database consisting three tables : ‘users’, ‘songs’ and ‘singers’. Now in our ‘songs’ table we have two table­cells, you should have probably noticed. One is ‘user_id’ and the other is ‘singer_id’. So presumably, a user inserts a song. And he has an ID. In my database I have inserted three users: first, second and third. So the have user IDs like 1,2 and 3 respectively.

And I also inserted 10 songs. And they have 10 song IDS of course respectively. Finally I have five singers who have their songs in the ‘songs’ table. Remember, these singers might have one or two songs. Someone may not have any song at all. Besides, these singers also have a foreign key ‘user_id’, that is, when a user inserts a singer’s name in that table his ID is inserted along with it. So there is a relationship among these three tables. And these relationship can be explained in many formatted versions. But Eloquent makes the job of managing and working with these relationships easy, and supports several different types of relationships. They are:

 One To One
 One To Many
 Many To Many
 Has Many Through
 Polymorphic Relations
 Many To Many Polymorphic Relations

Now we are going to explore these relationships one by one using Eloquent ORM in Laravel 4 also. After all, what is Eloquent ORM? Till now we have heard about MVC, that is Model­View­Controller methodology but practically we did not say anything about the Model part. Although primarily it has been mentioned that there are three main folders in ‘app’ – controllers, models, and views – that take active part in building a Laravel application.
Now, based on that theory, we assume that with each database table we have an associated Model. So that we can interact with the table much easily.
We have already seen that how Laravel has made the whole database operations quite easy and Eloquent is the new addition to it.
If you want a definition, Eloquent is the Active Record implementation for database operations. Now what is Active Record pattern? This is a technique that wrap database into objects. Suppose you have an ‘user’ table. You can present the data of that table as a class and every row as an object.
Now each database table has a corresponding Model that will do every operations that CRUD does. You know CRUD. Create, retrieve, update and delete. Now you can do them quite easily through Eloquent ORM. What is ORM? Object relation mapping. That is you can have a defined set of relations between the corresponding tables.
As we have seen in our database query building process, a table may have lot of relations among other tables. Eloquent ORM has a built in relationship. It makes our life much easier.
From Laravel 4.1 Eloquent becomes more powerful as it has attached a much requested feature – polymorphic Many to Many relationship. Now you need not write a lot of code to establish a polymorphic Many to Many relationship between tables. Eloquent does that quite easily. We have ‘users’ table and we have a ‘User’ class in our Model like this:
//code starting
//models/User.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
}
//end of code
Now in our route­level we have a code like this:
//code starting
//routes.php
Route::get('/', function()
{
$user = User::all();
var_dump($user);
});

//end of code
Since we have four users till now, the above output show them one by one throughout the key=>value pair. It starts from 0 and ends at 3. In the first few lines you notice something like this:

object(Illuminate\Database\Eloquent\Collection)[147]
protected ‘items’ =>
array (size=5)
0 =>
object(User)[141]
protected ‘table’ => string ‘users’ (length=5)
protected ‘hidden’ =>
array (size=2)

//output is incomplete
What it says? It says, this representation is of an object of Model User class. In the User class you have defined two properties already:
//code snippet from User.php
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
//code is incomplete
Now compare them with these two lines: protected ‘table’ => string ‘users’ (length=5) protected ‘hidden’ => array (size=2) …
I hope this comparison will inspire you to define more properties in the User class! And what can be defined, is being said in the above output.
There are lot of properties like ‘connection’, ‘relations’, ‘guarded’, ‘fillable’ etcetera. Now hopefully you understand that these properties can be defined in your User class. Not only in the User class in your Models folder, but in any class you write by yourself. Suppose we have another table called ‘contacts’. So we can create a Contact class in our Models folder. Let us create it with few properties.
//code starting
//models/Contact.php
class Contact extends Eloquent{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contacts';

}
//end of code
Now let us go to our routes.php and change the code to this:
//code starting
//routes.php
Route::get('/', function()
{
$usercontacts = Contact::all();
var_dump($usercontacts);
});

//end of code
We have the same output as before like ‘users’ table with one exception only. The only exception is in this line:

protected ‘table’ => string ‘contacts’ (length=8)

Basically, except this, every properties are predefined but anytime you can override them like this. If in your User class you write something like this:
//code starting
//User.php
class User extends Eloquent {
protected $guarded = array('password');
}
//end of User.php
It means, the ‘password’ of ‘users’ table is no longer mass-­assignable. You can even block all attributes from mass assignment like this:
protected $guarded = array(‘*’);
So the possibilities are endless. And we will later come back to these properties and discuss in a detailed manner. Before that I would look at some typically defined query building throughout our Models. Suppose we want to find the country of the first contacts. Laravel Eloquent ORM ships with reasonably moderate methodology that may help you to find it quite easily.
Consider this code:
Route::get('/', function()
{
$usercontacts = Contact::find(1);
var_dump($usercontacts­>country);
});
The output is as expected:

string ‘Mars’ (length=4)

But if we want to see all the contacts in a nicely formatted JSON way? Let us see:
Route::get('/', function()
{
$usercontacts = Contact::all();
foreach ($usercontacts as $key => $value) {
echo $key . "=" . $value . "
";
}
});

The JSON output is like this:

0={“id”:”1″,”user_id”:”1″,”address”:”Address of
Admin”,”country”:”Mars”,”phone”:”12445″}
1={“id”:”2″,”user_id”:”2″,”address”:”Address of
Sanjib”,”country”:”Jupiter”,”phone”:”456″}
2={“id”:”3″,”user_id”:”3″,”address”:”Address of
Debangshu”,”country”:”Moon”,”phone”:”567″}
3={“id”:”4″,”user_id”:”8″,”address”:”Address of
Mana”,”country”:”Sun”,”phone”:”234″}

It is quite obviously looks like Laravel has thought about it earlier and trying to use the advantage of JSON or JavaScript Object Notation. Essentially it is a human readable way of storing the value of an array or of an object as strings. Just pick up the first value from the first row of our Contacts table and see what it says.

0={“id”:”1″,”user_id”:”1″,”address”:”Address of
Admin”,”country”:”Mars”,”phone”:”12445″}

It says: our $contact object produces an array which has all the values of ‘contacts’ table. The first key which is 0 obviously; represents the first row of ‘contacts’ table.
Now you may ask, why Laravel chooses JSON? Yes, there are many reasons but one of them is definitely speed. The common usage of JSON is when a front end part of your application wants data from the back end without page load.
The same goal can be achievable by JavaScript with an AJAX request. Speed really matters when you deal with a pretty big application. Isn’t it?
It will not out of context if we slightly discuss about JSON here. I hope you would permit me to tell you something more. For a beginner it is good to learn that PHP starts serializing arrays and objects to JSON from its version 5.2.0. You may have heard about serialize() and unserialize() methods in PHP. It is nothing but converting an object to string and reversing to a new instance to get back its value.
Though I said JSON is a human readable way but practically it is not very readable as JSON stores data without whitespace between them. Why? As I said speed matters! Now back to our old discussion. The output means every contact row object has been included in an array. So we can break them to get more out of it like this:
Route::get('/', function()
{
$contact = Contact::all();
foreach ($contact as $value) {
var_dump($value);

}
});

Now the output is extremely important and it explicitly shows how Contact class behaves and creates its object. Here we see four contacts object with each having their properties well defined. We have extended our Contact class from Eloquent and thereby we have inherited those properties.
We are interested about the first part of the above output:

object(Contact)[141]
protected ‘table’ => string ‘contacts’ (length=8)
protected ‘connection’ => null
protected ‘primaryKey’ => string ‘id’ (length=2)
protected ‘perPage’ => int 15
public ‘incrementing’ => boolean true
public ‘timestamps’ => boolean true
protected ‘attributes’ =>
array (size=5)
‘id’ => string ‘1’ (length=1)
‘user_id’ => string ‘1’ (length=1)
‘address’ => string ‘Address of Admin’ (length=16)
‘country’ => string ‘Mars’ (length=4)
‘phone’ => string ‘12445’ (length=5)
protected ‘original’ =>
array (size=5)
‘id’ => string ‘1’ (length=1)
‘user_id’ => string ‘1’ (length=1)
‘address’ => string ‘Address of Admin’ (length=16)
‘country’ => string ‘Mars’ (length=4)
‘phone’ => string ‘12445’ (length=5)
protected ‘relations’ =>
array (size=0)
empty

……
You see this output is incomplete but it serves the purpose. There are lot of properties like ‘table’, ‘connection’, ‘attributes’, ‘original’ etcetera. Each property is an array. And ultimately Laravel produces them in JSON. Now to retrieve all data you just get the key and the value will come out like this:
//code starting
Route::get('/', function()
{
$contact = Contact::all();
foreach ($contact as $value) {
echo "Contact ID = " . $value­>id . "
";
echo "User ID = " . $value­>user_id .
"
";
echo "Address = " . $value­>address .
"
";
echo "Country = " . $value­>country .
"
";
echo "Phone = " . $value­>phone .
"

";
//var_dump($value) . "
";

}
});
//end of code
And the output is quite expected. It shows every contacts detail with user ID.
//the output

Contact ID = 1
User ID = 1
Address = Address of Admin
Country = Mars
Phone = 12445
Contact ID = 2
User ID = 2
Address = Address of Sanjib
Country = Jupiter
Phone = 456
Contact ID = 3
User ID = 3
Address = Address of Debangshu
Country = Moon
Phone = 567
Contact ID = 4
User ID = 8
Address = Address of Mana
Country = Sun
Phone = 234

//end of output
The crux of Eloquent model is this. Now let us do some query with our Eloquent Model. First we will check on the basis of age of the users. We have User class defined earlier. Now we want to check first two users who have their corresponding age more than 18.
//code starting
Route::get('/', function()
{
$users = User::where('age', '>', 18)­>take(2)­
>get();
foreach ($users as $user)
{
var_dump($user­->username);
}
});
//end of code
Remember, we have only three users in our users table who have age more than 18. We get first two.
//output

string ‘admin’ (length=5)
string ‘sanjib’ (length=6)

//end of output
It produces on the basis of user ID. It goes on 1,2,3 … and so on. If there are millions of users and you don’t need to process them all to avoid eating up your memory, one good method is chunk(). With only four users it is difficult to show you how it works but still we can have a try and have some fun indeed.
//code starting
User::chunk(100, function($users)
{
foreach ($users as $user)
{
//grab the $user here
}
});
//end of code
Inserting, updating or deleting with the help of Eloquent is quite easy as you have assumed already. You need not write a lot of code, instead you only write two or three lines of code to get your job done in a secured way.
//code starting
Route::get('/', function()
{
$user = new User();
$user­->username = 'NewUser';
$user­->password = password_hash('pass', PASSWORD_BCRYPT);
$user­->token = 'kljhnmbgfvcdsazxwetpouytresdfhjkmnbbvcdsxza';
$user-­>age = 27;
$user­->created_at = time();
$user­->updated_at = time();
$user-­>save();
return 'Saved NewUser';
});
//end of coding
Let us see how the new user ‘NewUser’ has been created in our ‘users’ table. To see his detail is very easy now. We know his age, that is 27. So write down this code:
//code starting
Route::get('/', function()
{
$users = User::where('age', '=', 27)­>get();
foreach ($users as $user) {
var_dump($user);
}
});

//end of coding
Now we have come to know how this new user object will look like when we use var_dump() method. There are several create() method of Eloquent Models. You can create many users at one go. Besides, you can retrieve and update any user with a minimum amount of coding like this:
//code starting
Route::get('/', function()
{
$user = User::find(2);
$user­>username = 'babu';
$user­->save();

return 'Saved!';
});
//end of coding
We know that second user was ‘sanjib’ but now it has successfully been saved to ‘babu’. Deleting is much easier than before. If we want to delete user ‘NewUser’ we need to write sql like this:

“DELETE FROM `sanjib`.`users` WHERE `users`.`id` = 10”?

Is it not fairly long? Because before this line you need to have to manually connect to your database etcetera. In Eloquent Models it is much easier as you have all things set up before hand. The code is simple:
//code starting
$user = User::find(10);
$user­->delete();

//end of coding
Before concluding our Eloquent discussion I would like to say something about those properties again. Whenever you are going to create a new class in your Eloquent Models, you have some properties already defined and set. Laravel has done that by default. We have seen those properties before. One of them is Timestamps. By default Eloquent maintain the created_at and updated_at columns of your database automatically and you need not bother about it.
Suppose, you run code like this to get all users belonging to the age less than 28.
//code starting
Route::get('/', function()
{
$users = User::where('age', 'take(2)->get();
foreach ($users as $user)
{
var_dump($user);
}

});
//end of code
We know the output and so we don’t repeat it anymore. But look at those properties, like ‘timestamps’, ‘fillable’ or ‘guarded’. As long as Eloquent maintains them, it is no problem but if we want to change them according to our criteria, then what happens?
Let us see to it. Suppose we want to make timestamps ‘false’ and also bring some changes to ‘fillable’ and ‘guarded’ properties. The code is like this in our User class before changing the properties:
//code starting
//models/User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's
JSON form.
*
* @var array
*/
protected $hidden = array('password',
'remember_token');

// public $timestamps = false;
// protected $fillable = array('username',
'token');
// protected $guarded = array('id',
'password');
}
//end of code
You see I have commented out those properties. Now we are going to change the User class and the final code is like this:
//code starting
//models/User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's
JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');

public $timestamps = false;
protected $fillable = array('username', 'token');
protected $guarded = array('id', 'password');
}
//end of code
Now see the changes in our output and compare them with the previous one. See each properties one by one:
//user defined properties
//of the first object
protected 'table' => string 'users' (length=5)
protected 'hidden' =>
array (size=2)
0 => string 'password' (length=8)
1 => string 'remember_token' (length=14)
public 'timestamps' => boolean false
protected 'fillable' =>
array (size=2)
0 => string 'username' (length=8)
1 => string 'token' (length=5)
protected 'guarded' =>
array (size=2)
0 => string 'id' (length=2)
1 => string 'password' (length=8)
//end of user defined properties
Database tables have relations among them. It is quite obviously true that one user would place her order knowing that the order will be added to her account. Three tables are associated instantly. Eloquent makes this managing part quite easy. In our previous database ‘sanjib’we have two related tables ‘users’ and ‘contacts’. In our User class let us write a method that corresponds to the Contact Model. That is, one User has one Contact. Laravel has the method already: hasOne() which passes one parameter that has relation with that Model.
//code starting
//models/User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's
JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public $timestamps = false;
protected $fillable = array('username', 'token');
protected $guarded = array('id', 'password');
public function contact()
{
return $this-­>hasOne('Contact');
}
}
//end of code
In our ‘users’ table, user name ‘mana’ has user ID 8. In ‘contacts’ she has primary ID 4 but has a corresponding user_id 8. So our intention is to reach ‘contacts’ table through User Model. For that reason we have added this methodology to the User Model:
public function contact()
{
return $this­->hasOne('Contact');
}

Now when we write in our routes.php, code like this:
//code starting
//routes.php
Route::get('/', function()
{
$contact = User::find(8)­->contact;
var_dump($contact);
});
//end of code
We actually reach ‘contacts’ table through our User Model and find whose user_id is 8. The output comes out directly from the ‘contacts’ table and produces the detailed contacts of user ‘mana’. The output is like this:
//output

object(Contact)[142]
protected ‘table’ => string ‘contacts’ (length=8)
protected ‘connection’ => null
protected ‘primaryKey’ => string ‘id’ (length=2)
protected ‘perPage’ => int 15
public ‘incrementing’ => boolean true
public ‘timestamps’ => boolean true
protected ‘attributes’ =>
array (size=5)
‘id’ => string ‘1’ (length=1)
‘user_id’ => string ‘1’ (length=1)
‘address’ => string ‘Address of Admin’ (length=16)
‘country’ => string ‘Mars’ (length=4)
‘phone’ => string ‘12445’ (length=5)
protected ‘original’ =>
array (size=5)
‘id’ => string ‘1’ (length=1)
‘user_id’ => string ‘1’ (length=1)
‘address’ => string ‘Address of Admin’ (length=16)
‘country’ => string ‘Mars’ (length=4)
‘phone’ => string ‘12445’ (length=5)
protected ‘relations’ =>
array (size=0)
empty
protected ‘hidden’ =>
array (size=0)
empty
protected ‘visible’ =>
array (size=0)
empty
protected ‘appends’ =>
array (size=0)
empty
protected ‘fillable’ =>
array (size=0)
empty
protected ‘guarded’ =>
array (size=1)
0 => string ‘*’ (length=1)
protected ‘dates’ =>
array (size=0)
empty
protected ‘touches’ =>
array (size=0)
empty
protected ‘observables’ =>
array (size=0)
empty
protected ‘with’ =>
array (size=0)
empty
protected ‘morphClass’ => null
public ‘exists’ => boolean true

//end of output
There is nothing new in it. Basically the SQL performed in this code is corresponding to this:
//SQL statement
select * from users where id = 8
select * from phones where user_id = 8
//end of SQL statement
This relationship is called One to One. You can define the inverse of the relationship on the Contact Model using belongsTo() method passing the name of the table as its first parameter. In that case in our Contact Class we will write code like this:
//code starting
//models/Contact.php
class Contact extends Eloquent{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contacts';
public function user()
{
return $this­>belongsTo('User');
}
}
//end of code
Now if we write this code in our routes.php:
//code starting
//routes.php
Route::get('/', function()
{
$contact = Contact::find(4)­>user;
var_dump($contact);
});

//end of code
It means in our ‘contacts’ table we search throughout the ID and see whether it has a corresponding user_id with that. Presently, in our ‘contacts’ table we have corresponding user_id 10 with the contacts ID 4. This relationship means the contacts ID 4 has all the user’s detail in the ‘users’ table and it looks upon on its corresponding user_id to see what is the number there. In this case, contacts ID 4 has a corresponding user_id 10. So it is convinced that in ‘users’ table it has an ID 10. In users table the ID 10 belongs to our newly created User ‘NewUser’. Few pages back, we have created ‘NewUser’ through insert method using Eloquent.
Ultimately, it brings out the output of ‘NewUser’. Now you need to understand that little tricky difference between these two methods:
//User.php
public function contact()
{
return $this­->hasOne('Contact');
}
//Contact.php
public function user()
{
return $this-­>belongsTo('User');
}
This hasOne() in User Class searches for corresponding user_id in ‘contacts’ table and belongsTO() in Contact.php just relates its primary ID to the corresponding user_id in that table. Both ways, user_id plays the vital role and defines that One to One relationship; but, in a different way.
The same way very easily we can establish one to many relationship among tables. Suppose one user has many posts in our ‘posts’ table. How can we get his all articles in one go?
There is one method hasMany() that passes similarly parameters that can do that SQL query very easily. In our User Model first we should define that method. This way:
//code starting
//models/User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's
JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public $timestamps = false;
protected $fillable = array('username', 'token');
protected $guarded = array('id', 'password');
public function contact()
{
return $this­->hasOne('Contact');
}

public function post()
{
return $this­->hasMany('Post');
}
}
//end of code
And after that we will catch every article written by any user_id mentioned in ‘posts’ table in our routes.php file. And the code is
//code starting
//routes.php
Route::get('/', function()
{
$posts = User::find(10)­>post;
foreach ($posts as $value) {
echo "This Post made by User ID : {$value­
>user_id}
";
echo "Intro: " . $value­>intro . "
";
echo "Article: " .$value­>article .
"
";
echo "Tags: " .$value­>tag .
"

";
}
});
//end of code
Finally we get all the posts submitted by the ‘NewUser’ whose user ID is 10. And the output is like this:
//output

This Post made by User ID : 10
Intro: intro1
Article: article1 laravel tutorial for beginners, laravel, laravel tutorial
Tags: laravel tutorial for beginners, laravel, laravel tutorial
This Post made by User ID : 10
Intro: intro3
Article: article 3 laravel tutorial for beginners, laravel, laravel tutorial
Tags: laravel learner, laravel, laravel tutorial
This Post made by User ID : 10
Intro: intro 4
Article: article 4 laravel tutorial for beginners, laravel, laravel tutorial
Tags: laravel learner, laravel, laravel tutorial

//end of output
Basically the articles shown here are for testing purpose. Now you can, hopefully, write your own CMS based on Laravel. Finally we will check Many to Many relationship. There are some situations where users may have different roles at the same time. Let us first add a table to our database : roles. Then assign some column like id, name, created_at and updated_at. Now we have four roles: Administrator, Moderator, Contributor and Member. We have had five users. Some of them have common roles like user ‘admin’ is Administrator, Moderator and Contributor. The user ‘NewUser’ is also like that. Rest of them have different roles like user ‘babu’ is Moderator and as well as Contributor etcetera. This is a very complex relationship but Laravel ships with a very simple solution. It has a method called belongsToMany() method that would define that relationship but we need an intermediary table to join two tables: users and roles. That intermediary table is called ‘role_user’. The name is derived from the alphabetical order of the related Model names. The table ‘role_user’ should have two columns: role_id and user_id. So that you can build Many to Many relations quite easily.
We have role_user table filled up with different responsibilities. You can run that SQL at one go to test your application. Just create the table ‘role_user’ in your database ‘sanjib’ and run this SQL:
//role_user.SQL
-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 30, 2015 at 08:43 PM
-- Server version: 5.5.41-0ubuntu0.14.04.1
-- PHP Version: 5.5.21-1+deb.sury.org~precise+2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";Laravel Learner - 607
/*!40101 SET
@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET
@OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET
@OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `sanjib`
--
-- --------------------------------------------------------
--
-- Table structure for table `role_user`
--
CREATE TABLE IF NOT EXISTS `role_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
--Laravel Learner - 608
-- Dumping data for table `role_user`
--
INSERT INTO `role_user` (`id`, `user_id`, `role_id`, `created_at`, `updated_at`)
VALUES
(1, 1, 1, '2015-03-30 15:10:21', '0000-00-00 00:00:00'),
(2, 1, 2, '2015-03-30 15:10:46', '0000-00-00 00:00:00'),
(3, 1, 3, '2015-03-30 15:10:55', '0000-00-00 00:00:00'),
(4, 10, 1, '2015-03-30 15:11:06', '0000-00-00 00:00:00'),
(5, 10, 2, '2015-03-30 15:11:22', '0000-00-00 00:00:00'),
(6, 10, 3, '2015-03-30 15:11:31', '0000-00-00 00:00:00'),
(7, 2, 2, '2015-03-30 15:11:43', '0000-00-00 00:00:00'),
(8, 2, 3, '2015-03-30 15:11:51', '0000-00-00 00:00:00'),
(9, 8, 3, '2015-03-30 15:12:38', '0000-00-00 00:00:00'),
(10, 8, 4, '2015-03-30 15:12:45', '0000-00-00 00:00:00'),
(11, 3, 3, '2015-03-30 15:12:53', '0000-00-00 00:00:00'),
(12, 3, 4, '2015-03-30 15:12:59', '0000-00-00 00:00:00');
/*!40101 SET
CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET
CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET
COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
//end of role_user.SQL
Now first of all we would set the method in our User Model like this:
//code starting
//models/User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements
UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's
JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public $timestamps = false;
protected $fillable = array('username', 'token');
protected $guarded = array('id', 'password');

public function contact()
{
return $this­->hasOne('Contact');
}

public function post()
{
return $this­->hasMany('Post');
}

public function role()
{
return $this-­>belongsToMany('Role');
}
}
//end of code
In this method:
public function role()
{
return $this­->belongsToMany('Role',
'role_user');
}
You can explicitly pass the pivot table as the second parameter. Suppose you want to use table name ‘users_role’ instead ‘role_user’ then you can write:
public function role()
{
return $this-­>belongsToMany('Role', 'users_role');
}

That is it. And equally now you can use the inversion in the Role Model. The code is like this:
//code starting
//models/Role.php

class Role extends Eloquent{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'roles';

public function user()
{
return $this-­>belongsToMany('User');
}
}
//end of code
Now the time has come to test our code. Many to Many relationship works like a breeze now. The first user ‘admin’ has three different roles: Administrator, Moderator and Contributor. Let us check whether in our routes we can get it or not:
//code starting
//routes.php
Route::get('/', function()
{
$roles = User::find(1)-­>role;
foreach ($roles as $value) {
var_dump($value);
}
});

//end of code
We are trying to find out what kind of roles does the user ‘admin’ have? The user ‘admin’ has three roles: Administrator, Moderator and Contributor. It has been shown up throughout the User Model. Now we can have an inversion of this Model. Now we are going to find out which users are Administrator or Moderator or Contributor or Member. Like, in our routes.php we can write the code this way:
//code starting
//routes.php
Route::get('/', function()
{
$roles = Role::find(1)­->user;
foreach ($roles as $value) {
var_dump($value);
}
});

//end of code
In this code, we actually want to find out who are Administrators? Because, role ID 1 is Administrator. Here are two users who are Administrators. They are ‘admin’ and ‘NewUser’. The detailed data about them has been taken out from the ‘users’ table. From ‘roles’ table through the Role Model you can search any role that has been assigned to the users. There could be thousand of Members or Contributors. But in a few lines of codes Laravel make your task quite simpler. In the next chapter we will see some more features of Laravel that deal with database.

https://leanpub.com/laravel5learneasy/embed


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s