Laravel is one of the most popular PHP frameworks, and according to the Laravel official website, it is a framework for Web Artisans. Laravel is beautiful, powerful, and has tons of features that can enable developers to write efficient and quality code. The Laravel official documentation is well written and very easy to understand. So, let's play a little with Laravel.
Installation is very easy and simple. Let's use Composer to install Laravel. We discussed Composer in Appendix A. Issue the following command in the terminal to install and create a project in Laravel:
composer create-project --prefer-dist laravel/laravel packt
If Composer is not installed globally on the system, place composer.phar
in a directory where Laravel should be installed and issue the following command in the terminal at the root of this directory:
php composer.phar create-project --prefer-dist laravel/laravel packt
Now, Laravel will be downloaded, and a new project with the name packt
will be created. Also, Composer will download and install all the dependencies for the project.
Open the browser and head to the project's URL, and we will be welcomed with a nice simple page saying Laravel 5.
Laravel provides tons of features, and we will only discuss a few here.
Laravel provides powerful routing. Routes can be grouped, and prefixes, namespaces, and middleware can be defined for route groups. Also, Laravel supports all HTTP methods, including POST
, GET
, DELETE
, PUT
, OPTIONS
, and PATCH
. All the routes are defined in the routes.php
file in the application's app
folder. Take a look at the following example:
Route::group(['prefix' => 'customer', 'namespace' => 'Customer', 'middleware' => 'web'], function() { Route::get('/', 'CustomerController@index'); Route::post('save', 'CustomerController@save'); Route::delete('delete/{id}', 'CustomerController@delete'); });
In the preceding snippet, we created a new routes group. This will be only used when the URL has a prefixed customer. For example, if a URL is similar to domain.com/customer
, this group will be used. We also used a customer namespace. Namespacing allows us to use standard PHP namespaces and divide our files in subfolders. In the preceding example, all customer controllers can be placed in the Customer subfolder in the Controllers
directory, and the controller will be created as follows:
namespace App\Http\Controllers\Customer use App\Http\{ Controllers\Controller, Requests, }; use Illuminate\Http\Request; Class CustomerController extends Controller { … … }
So, namespacing a route group enables us to place our controller files in subfolders, which are easy to manage. Also, we used the web middleware. Middleware provides a way to filter the request before entering the application, which enables us to use it to check whether a user is logged in or not, the CSRF protection, or whether there are any other actions that can be performed in a middleware and need to be performed before the request is sent to application. Laravel comes with a few middleware, including web
, api
, auth
, and so on.
If a route is defined as GET
, no POST
request can be sent to this route. It is very convenient, which enables us to not worry about the request method filtering. However, HTML forms do not support the HTTP methods like DELETE
, PATCH
, and PUT
. For this, Laravel provides method spoofing, in which a hidden form field with name _method
and the value of the HTTP method is used to make this request possible. For example, in our routes group, to make the request possible to delete a route, we need a form similar to the following:
<form action="/customer/delete" method="post"> {{ method_field('DELETE') }} {{ csrf_field() }} </form>
When the preceding form is submitted, it will work, and the delete route will be used. Also, we created a CSRF hidden field, which is used for CSRF protection.
Note
Laravel routing is very interesting, and it is a big topic. More in-depth detail can be found at https://laravel.com/docs/5.2/routing.
Eloquent ORM provides active records to interact with the database. To use Eloquent ORM, we have to just extend our models from the Eloquent model. Let's have a look at a simple user model, as follows:
namespace App; use Illuminate\Database\Eloquent\Model; class user extends Model { //protected $table = 'customer'; //protected $primaryKey = 'id_customer'; … … }
That's it; we have a model that can handle all the CRUD operations now. Note that we commented the $table property
and did the same for $primaryKey
. This is because Laravel uses a plural name of the class to look for the table unless the table is defined with the protected $table property
. In our case, Laravel will look for table name users and use it. However, if we want to use a table named customers
, we can just uncomment the line, as follows:
protected $table = 'customers';
Similarly, Laravel thinks that a table will have a primary key with the column name id
. However, if another column is needed, we can override the default primary key, as follows:
protected $primaryKey = 'id_customer';
Eloquent models also make it easy for timestamps. By default, if the table has the created_at
and updated_at
fields, then these two dates will be generated automatically and saved. If no timestamps are required, these can be disabled, as follows:
protected $timestamps = false;
Saving data to the table is easy. The table columns are used as properties of the models, so if our customer
table has columns such as name
, email
, phone
, and so on, we can set them as follows in our customer
controller, mentioned in the routing section:
namespace App\Http\Controllers\Customer use App\Http\{ Controllers\Controller, Requests, }; use Illuminate\Http\Request; use App\Customer Class CustomerController extends Controller { public function save(Request $request) { $customer = new Customer(); $customer->name = $request->name; $customer->email = $request->email; $customer->phone = $request->phone; $customer->save(); } }
In the preceding example, we added the save
action to our controller. Now, if a POST
or GET
request is made along the form data, Laravel assigns all the form-submitted data to a Request object as properties with the same names as that of the form fields. Then, using this request object, we can access all the data submitted by the form either using POST
or GET
. After assigning all the data to model properties (the same names as those of table columns), we can just call the save method. Now, our model does not have any save method, but its parent class, which is the Eloquent model, has this method defined. However, we can override this save
method in our model
class in case we need some other features in this method.
Fetching data from the Eloquent model is also easy. Let's try an example. Add a new action to the customer
controller, as follows:
public function index() { $customers = Customer::all(); }
We used the all()
static method in the model, which is basically defined in the Eloquent model, which, in turn, fetches all the data in our customers
table. Now, if we want to get a single customer by the primary key, we can use the find($id)
method, as follows:
$customer = Customer::find(3);
This will fetch the customer with the ID 3
.
Updating is simple, and the same save()
method is used, as shown here:
$customer = Customer::find(3); $customer->name = 'Altaf Hussain'; $customer->save();
This will update the customer with the ID 3
. First, we loaded the customer
, then we assigned new data to its properties, and then we called the same save()
method. Deleting the model is simple and easy and can be done as follows:
$customer = Customer::find(3); $customer->delete();
We first loaded the customer with the ID 3
, and then we called the delete
method, which will delete the customer with the ID 3
.
Note
Laravel's Eloquent models are very powerful and provide lots of features. These are well explained in the documentation at https://laravel.com/docs/5.2/eloquent. The Laravel database section is also worth reading and can be found at https://laravel.com/docs/5.2/database.
Artisan is the command-line interface provided with Laravel, and it has some nice commands that can be used for quicker operations. It has lots of commands, and a full list can be seen using the following command:
php artisan list
This will list all the options and commands available.
Note
The php artisan
command should be run in the same directory in which the artisan
file is located. It is placed at the root of the project.
Some of the basic commands are as follows:
make:controller
: This command creates a new controller in theControllers
folder. The command can be used as follows:php artisan make:controller MyController
If a namespaced controller is required, as it happened before with the
Customer
namespace, it can be done as follows:php artisan make:controller Customer/CustomerController
This command will create
CustomerController
in theCustomer
folder. If theCustomer
folder is not available, it will create the folder as well.make:model
: This creates a new model in theapp
folder. The syntax is the same as themake:controller
command, as follows:php artisan make:model Customer
For the namespaced models, it can be used as follows:
php artisan make:model Customer/Customer
This will create the
Customer
model in theCustomer
folder and use theCustomer
namespace for it.make:event
: This creates a newevent
class in theEvents
folder. It can be used as follows:php artisan make:event MyEvent
make:listener
: This command creates a new listener for an event. This can be used as follows:php artisan make:listener MyListener --event MyEvent
The preceding command will create a new listener for our
MyEvent
event. We have to always mention the event for which we need to create a listener using the--event
option.make:migration
: This command creates a new migration in the database/migrations folder.php artisan migrate
: This runs all the available migrations that are not executed.php artisan optimize
: This command optimizes the framework for better performance.php artisan down
: This puts the application in maintenance mode.php artisan up
: This command brings the application back live from the maintenance mode.php artisan cache:clear
: This command clears the application cache.php artisan db:seed
: This command seeds the database with records.php artisan view:clear
: This clears all the compiled view files.Note
More detail about the Artisan console or Artisan CLI can be found in the documentation at https://laravel.com/docs/5.2/homestead.
Migrations is another powerful feature in Laravel. In migrations, we define the database schemas—whether it creates tables, removes tables, or adds/updates columns in the tables. Migrations are very convenient in deployment and act as version control for the database. Let's create a migration for our customer table that is not available in the database yet. To create a migration, issue the following command in the terminal:
php artisan make:migration create_custmer_table
A new file in the database/migrations
folder will be created with the filename create_customer_table
prefixed with the current date and a unique ID. The class is created as CreateCustomerTable
. This is a class as follows:
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCustomerTable extends Migrations { //Run the migrations public function up() { //schemas defined here } public function down() { //Reverse migrations } }
The class will have two public methods: up()
and down()
. The up()
method should have all the new schemas for the table(s). The down()
method is responsible for reversing the executed migration. Now, lets add the customers
table schema to the up()
method, as follows:
public function up() { Schema::create('customers', function (Blueprint $table) { $table->increments('id', 11); $table->string('name', 250) $table->string('email', 50); $table->string('phone', 20); $table->timestamps(); }); } public function down() { Schema::drop('customers'); }
In the up()
method, we defined the schema and table name. Columns for the table are individually defined, including the column size. The increments()
method defines the autoincrement column, which, in our case, is the id
column. Next, we created three string columns for name
, email
, and phone
. Then, we used the timestamps()
method, which creates the created_at
and updated_at
timestamp columns. In the down()
method, we just used the drop()
method of the Schema
class to drop out the customers
table. Now, we need to run our migrations using the following command:
php artisan migrate
The preceding command will not only run our migration but will also run all those migrations that are not executed yet. When a migration is executed, Laravel stores the migration name in a table called migrations
, from where Laravel decides which migrations it has to execute and which to skip.
Now, if we need to roll back the latest executed migration, we can use the following command:
php artisan migrate:rollback
This will roll back to the last batch of migrations. To roll back all the migrations of the application, we can use the reset command, as follows:
php artisan migrate:reset
This will roll back the complete application migrations.
Migrations make it easy for deployment because we won't need to upload the database schemas every time we create some new changes in the tables or database. We will just create the migrations and upload all the files, and after this, we will just execute the migration command, and all the schemas will be updated.
Laravel comes with its own template language called Blade. Also, Blade template files support plain PHP code. Blade template files are compiled to plain PHP files and are cached until they are changed. Blade also supports layouts. For example, the following is our master page layout in Blade, placed in the resources/views/layout
folder with the name master.blade.php
. Take a look at the following code:
<!DOCTYPE html> <html> <head> <title>@yield('title')</title> </head> <body> @section('sidebar') Our main sidebar @show <div class="contents"> @yield('content') </div> </body> </html>
In the preceding example, we had a section for the sidebar that defines a content
section. Also, we had @yield
, which displays the contents of a section. Now, if we want to use this layout, we will need to extend it in the child template files. Let's create the customers.blade.php
file in the resources/views/
folder and place the following code in it:
@extend('layouts.master') @section('title', 'All Customers') @section('sidebar') This will be our side bar contents @endsection @section('contents') These will be our main contents of the page @endsection
As can be seen in the preceding code, we extended the master
layout and then placed contents in every section of the master
layout. Also, it is possible to include different templates in another template. For example, let's have two files, sidebar.blade.php
and menu.blade.php
, in the resources/views/includes
folder. Then, we can include these files in any template, as follows:
@include(includes.menu) @include(includes.sidebar)
We used @include
to include a template. The dot (.
) indicates a folder separation. We can easily send data to Blade templates or views from our controllers or routers. We have to just pass the data as an array to a view, as follows:
return view('customers', ['count => 5]);
Now, count
is available in our customers
view file and can be accessed as follows:
Total Number of Customers: {{ count }}
Yes, Blade uses double curly braces to echo a variable. For control structures and loops, let's have another example. Let's send data to the customers
view, as follows:
return view('customers', ['customers' => $allCustomers]);
Now, our customers
view file will be similar to the following if we want to display all the customers
data:
… … @if (count($customers) > 0) {{ count($customers) }} found. <br /> @foreach ($customers as $customer) {{ $customer->name }} {{ $customer->email }} {{ $customer->phone }} <br> @endforeach @else Now customers found. @endif; … …
All the preceding syntax looks familiar as it is almost the same as plain PHP. However, to display a variable, we have to use double curly braces {{}}
.
Note
A nice and easy-to-read documentation for Blade templates can be found at https://laravel.com/docs/5.2/blade.
We only discussed a few basic features in the previous section. Laravel has tons of other features, such as Authentication and Authorization, which provide an easy way to authenticate and authorize users. Also, Laravel provides a powerful caching system, which supports file-based cache, the Memcached, and Redis cache. Laravel also provides events and listeners for these events, which is very convenient when we want to perform a specific action and when a specific event occurs. Laravel supports localization, which enables us to use localized contents and multiple languages. Laravel also supports task scheduling and queues, in which we schedule some tasks to run at a specific time and queue some tasks to be run when their turn arrives.