Learning Laravel's Eloquent - Sample Chapter
Learning Laravel's Eloquent - Sample Chapter
ee
Sa
pl
from Vasto, a wonderful city on the Italian eastern coast. He actually lives in Rome,
where he is studying computer engineering. He received his first PC at the age of six,
and since then, they have never separated. It's not all about computers, however; he
also likes to travel, add new items to his movie collection, and create new awesome
experiences. This book is a perfect example.
"Never stop" is his key.
He is the founder of Laravel-Italia, the Italian Laravel community. He works as a
freelancer developer and consultant, but he also writes for Sitepoint, in the PHP
section, and HTML.IT, the first portal about information technology in Italy.
He started his first job in web development when he was 15 years old.
In the past, he has translated three books, which are Laravel: Code Happy
(by Dayle Rees), Code Bright (by Dayle Rees), and Laravel Testing: Decoded
(by Jeffrey Way).
Preface
If you are associated with the field of web development, you know how important
data is. The web runs on data, so it's essential for developers to think of quick and
effective ways to deal with it. Eloquent is an awesome ORM that comes with the
Laravel PHP framework. It is unique and is very beneficial to developers as it allows
them to define models, relationships, and many complex operations with a really
easy and intuitive syntax, without sacrificing performance. Performing an interesting
number of operations on multiple tables without writing long queries with objects
will be a bed of roses.
This book will take you through developing brilliant data-based applications with
Eloquent, the Laravel framework ORM.
You will do the following:
Get to grips with the power of relationships and how Eloquent handles them
Preface
Chapter 3, The Most Important Element the Model!, will help us implement some
"create," "read," "update," and "delete" logic for our items. We will also explore
some useful methods and features of the model class.
Chapter 4, Exploring the World of Relationships, will help us discover how to work with
different types of relationships and how to query and use them in a comfortable
and clean way. Also, we will learn how to insert and delete related models in our
database, or update existing ones.
Chapter 5, Using Collections to Enhance Results, will talk about collections. We will
work with some results transformation methods and with the elements that make
up a collection.
Chapter 6, Everything under Control with Events and Observers, will allow us to learn
everything about the events in the context of Eloquent models. Right after, we will
cover model events and model observers.
Chapter 7, Eloquent without Laravel!, will explore the structure of the database
package and see what is inside it. After that, we will learn how to install the
"illuminate/database" package separately for your project and how to configure it
for its first use. Yes, exactly: Eloquent without Laravel!
Chapter 8, It's Not Enough! Extending Eloquent, Advanced Concepts, will explore
two different ways to extend Eloquent, and move on to learn about the
Repository pattern.
[1]
Trust me.
Summary
Installing Composer
The installation procedure is ridiculously easy. All you have to do, is to go on
the Download page of the Composer website and find the right method for your
operating system.
[2]
Chapter 1
Once Composer is installed, I suggest putting its path in the PATH variable of your
system, in order to use it wherever you want. There are many ways to do it, which
depend on your operating system. Let's look at each.
On Linux, you can move Composer to the right directory simply with the
following command:
mv composer.phar /usr/local/bin/composer
The same goes for OS X, but sometimes, the usr directory doesn't exist.
You must create usr/local/bin manually.
Finally, on Windows, you must open the control panel and type
rest for you. Once in the right window, you will get a list of all environment
variables. Find PATH and add the composer installation path to it.
3. After that, save the file and type the following in your project directory:
composer update
Let's say that you have an index.php file as a start file for your application. You will
have to perform something like the following:
<?php // index.php file
require('vendor/autoload.php');
// your code here...
Nothing more!
Why am I showing this to you? Well, Laravel and Eloquent are Composer packages.
So, in order to use it and create a Laravel application, you have to know how the
mechanism works!
With this command, you can create a new project using a specific package
as a base. You will use this command to create a new Laravel project using
the following syntax:
composer create-project laravel/laravel my_project_folder
These are two similar commands; they are similar, but not the same.
When you specify your dependencies in the composer.json file, you
can use install to install them. If you already installed them but you
want to update your dependencies to a newer version, use update.
[4]
Chapter 1
You can use require to include dependencies in your project on the fly.
Here's an example of Monolog inclusion using require:
composer.phar require monolog/monolog:1.12.0
This command updates Composer itself. Just a few seconds, and you are up
and running again!
[5]
Last but not least, the fun (and useful) thing about Vagrant is that you can put a
specific box under version control. So, for every new team member, all you have to
do is to clone the repository and start the machine.
This looks complicated, but it is not. With Vagrant you can easily download a box
(a ready-to-use virtual machine with all the tools and applications you need) and
start it with a simple command from the shell as shown:
$ vagrant up
[6]
Chapter 1
The Laravel community knows a couple of things about Vagrant and makes up a
Vagrant Box to help you in your job.
Homestead is the official Vagrant Box for Laravel and already has everything you
need to get started. You will find it (already installed and working), by default:
Ubuntu 14.04
PHP 5.6
Redis
HHVM
Memcached
nginx
Beanstalkd
MySQL
Laravel Envoy
PostgreSQL
Not too bad for a tool box that you can prepare in a matter of minutes!
Now let's stop discussing and install Homestead.
[7]
Installing Homestead
First of all, ensure that you have already installed VirtualBox (https://www.
virtualbox.org/) and Vagrant (https://www.vagrantup.com/). You can install
them on every operating system, so feel free to use whichever you want.
If you want to work with a good shell on Windows, I suggest
you use Cmder (http://bliker.github.io/cmder/).
While writing this book, I referred to the same link.
Next, we can add Homestead to our local boxes. This means that Vagrant will
download the Homestead box in order to be used locally.
You can do it with a simple command:
vagrant box add laravel/homestead
You will have to wait a couple of minutes to download the box. So, if you want to
have a coffee, this is the perfect moment.
Here, you don't have to worry about where Vagrant is placing the box,
as it is going to save it locally in the Vagrant folder. In the future, every
time you will need a specific box, Vagrant will clone and use it.
Alright, your box is now on your local machine and ready to be started.
However, accordingly to your local machine settings, you can install Homestead
in two different ways. They are both present in the official Laravel documentation,
so they are both official.
[8]
Chapter 1
After that, you can initialize your machine. Use the init command:
homestead init
This will create a ~/.homestead folder with a Homestead.yaml inside of it. This file
will be used by Vagrant at the virtual machine start.
Here, HomesteadFolder is the place you chose for your VM files. After the
clone process, use cd to get into the folder and start the init script using the
following command:
bash init.sh
Configuring Homestead
Before we go forward, let's take a look at the default Homestead.yaml file.
--ip: "192.168.10.10"
memory: 2048
cpus: 1
[9]
If you are unfamiliar with this syntax, no problem; it's a simple YAML (YAML ain't
a markup language) markup file. It is a very readable way to specify settings, and
Homestead uses it. Here, you can choose the IP address for your virtual machine and
other settings. Tweak the configuration file accordingly to your needs.
1. Do you see the authorize property in the Homestead.yaml file? Well, we
are going to set up our SSH key and put its path there. If it scares you, don't
worry; it is just a command.
ssh-keygen -t rsa -C "you@homestead"
[ 10 ]
Chapter 1
2. Put the generated SSH key path in the authorize property of Homestead.
yaml, as shown in the following:
authorize: ~/.ssh/id_rsa.pub
Also, this means that you will have to create a Code folder in your user
folder. This local folder will be mapped to a /home/vagrant/Code folder
on the VM; every change that you make there will be reflected on the virtual
machine and vice versa.
You can customize this mapping to your needs.
4. Next, let's take a look at the sites property. Here's what you can see in a
default setup:
sites:
- map: homestead.app
to: /home/vagrant/Code/Laravel/public
You can define a custom domain for every project, which is a really
comfortable way to work with your projects, as you will no longer need to
test your project with an IP (like 192.168.10.10), only a simple local domain,
such as myproject.dev.
[ 11 ]
5. This is a good point to define a separate site for our project. So, feel free to
add these lines to your file:
- map: eloquent.dev
to: /home/vagrant/Code/EloquentJourney/public
6. Next, go to your host's file (on the host machine) and add this record:
192.168.10.10 eloquent.dev
You can see how you need to add it in the following screenshot:
7. The last thing we are going to see here is the database property. For every
name you add here, Homestead will automatically create a database to work
with. So, edit the property to something like this:
databases:
- homestead
- eloquent_journey
[ 12 ]
Chapter 1
We have nothing more to do here; our setup is complete, and now we are ready to
boot up our virtual machine and use it.
Here, MyHomesteadImprovedVM will be the containing folder of all the VM's files.
After the clone procedure, just type the following:
vagrant up
[ 13 ]
Obviously, you can use whatever you want to deal with your database. However,
I wanted to show you Adminer because it is what I am going to use to show, from
time to time, some query results or various examples. So, it would be good if you get
more familiar with this tool.
[ 14 ]
Chapter 1
Installing Laravel
Before going further, remember that Laravel has some prerequisites. You will need
the following:
Obviously, if you have installed Homestead, everything is already in its right place.
1. All you have to do is to boot up the VM with the following command:
homestead up
2. And when the bootstrap procedure is done, use the following command to
get in the machine via SSH:
homestead ssh
Having said that, as you may have experienced from Homestead, Laravel also gives
you two different ways to install it and create a new project.
The first one is done using a specific tool, the Laravel installer tool. It's a CLI
tool that you can install as a global Composer package.
[ 15 ]
Installing the tool is easy. Just open the terminal and type the following:
composer global require "laravel/installer=~1.1"
As you saw before, we are executing the require command with the global
keyword. This means that the installer tool package will be saved in the Composer's
global folder and the tool will be available everywhere.
If you have any problems running the tool, just be sure to put
~/.composer/vendor/bin in the PATH environment variable.
Otherwise, it won't work!
Here, ProjectName stands for the folder name that you want to use as the root of
your new Laravel project.
Nothing more to do here! Your Laravel project is now fully installed in your
specified folder.
Be sure to configure the right permissions on your folders and
ensure you take a good look at the URL rewriting rules. If you take
a look at the Laravel-dedicated documentation page (http://
laravel.com/docs/5.0/installation#pretty-urls), you
can learn how to do it on Apache or nginx.
[ 16 ]
Chapter 1
What are you waiting for? Let's start! First of all, create a new project (using your
favorite method). We will call our new project EloquentJourney. Type the following
in your server folder:
laravel new EloquentJourney
Wait a few seconds to build the project, and after the installation procedure, you are
done! You can use cd to get into your new folder and see what's there.
Cool! All right, but what are we going to do now? There are thousands of files here
and in other subfolders! Don't worry. Take a breath and follow me. First of all, we
need to do some practice with the Laravel configuration system in order to set up an
appropriate database connection.
Without it, we could not use Eloquent!
[ 17 ]
This means that the app.debug configuration item is set on the Boolean value true.
Laravel uses these values all around the framework code, and you can use them too
with the \Config class.
Specifically, if you want to retrieve a specific item value, you have to call the get()
method, as follows:
$myItem = \Config::get('item.name');
var_dump($myItem);
// true
You can also set a specific Config value at runtime, this time using the set()
method, as follows:
\Config::set('item.name', 'my value!');
$myItem = \Config::get('item.name');
var_dump($myItem);
// "my value!"
[ 18 ]
Chapter 1
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
'mysql',
'localhost',
'homestead',
'homestead',
'secret',
'utf8',
'utf8_unicode_ci',
'',
false,
'pgsql',
env('DB_HOST', 'localhost'),
env('DB_DATABASE', 'forge'),
env('DB_USERNAME', 'forge'),
env('DB_PASSWORD', ''),
'utf8',
[ 19 ]
=> '',
=> 'public',
],
'sqlsrv' => [
'driver'
=>
'host'
=>
'database' =>
'username' =>
'password' =>
'prefix'
=>
],
'sqlsrv',
env('DB_HOST', 'localhost'),
env('DB_DATABASE', 'forge'),
env('DB_USERNAME', 'forge'),
env('DB_PASSWORD', ''),
'',
],
'migrations' => 'migrations',
'redis' => [
'cluster' => false,
'default' =>
'host'
'port'
'database'
],
[
=> '127.0.0.1',
=> 6379,
=> 0,
],
];
The two most important items are default and connections. In this second item,
connections, we are storing all the information we need to connect to our databases.
By default, you will find many examples. In fact, here you can see the sqlite, then
mysql, and also sqlsrv connections.
Every connection has a driver. The driver element indicates the used database
for that connection. If you want, you can specify more than one connection, when
necessary. The default element represents the chosen connection.
[ 20 ]
Chapter 1
Let's delete everything and replace the default and connections elements with
the following:
'default' => 'eloquentJourney',
'connections' => [
'eloquentJourney' => [
'driver'
=> 'mysql',
'host'
=> 'localhost',
'database' => 'eloquent_journey',
'username' => 'homestead',
'password' => 'secret',
'charset'
=> 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'
=> '',
'strict'
=> false,
],
],
Summary
We did it!
We prepared everything that is needed to work with Laravel and Eloquent. We set
up a local development server, learned the basics of Composer to correctly manage
our dependencies, installed a couple of more useful tools, and, finally, successfully
configured our database connection. Not bad for the first chapter, huh?
However, we have just begun, and our journey inside Eloquent is at the very
beginning. We are ready to leave our safe house, go into the darkest corner of the
Eloquent ORM to explore it, and understand all of its secrets.
It will be a great ride. And now, let's explore our first topic on our way: the Schema
Builder and the migrations system, to build the perfect database!
[ 21 ]
www.PacktPub.com
Stay Connected: