DatabaseDevelop Faster with the Laravel PHP Framework

Develop Faster with the Laravel PHP Framework

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Laravel is an increasingly popular PHP framework that can help you develop better, more sustainable code in a shorter amount of time. By using its built-in features and concepts, you can save a significant amount of time, thus increasing your productivity and competitiveness.

Laravel offers a number of key features, including:

  • Eloquent ORM
  • Authentication
  • Events
  • Queues
  • Caching

Each of these features is covered in the following sections.

Eloquent ORM in Laravel

Eloquent ORM (object relational mapping) is an ActiveRecord implementation for working with your database. There is no need to write SQL queries anymore—just define the database tables and relations between them and Eloquent will do the rest of the job.

Each database file has its own class (model) which is used to interact with the table. Here is a sample model:

//Each model is a a child class of the Eloquent class
class Category extends Eloquent {

   // Table name. If omitted, Eloquent would assume that table name is the plural of class name (categories)
   protected $table = 'category';

   // Primary key. If omitted, the key 'id' would be used
   protected primaryKey = 'category_id';

   // If set to false, removes created_at and updated_at table columns
   public $timestamps = false;
}

This model represents the following SQL database:

CREATE TABLE IF NOT EXISTS 'category' (
   'category_id' INT(10) NOT NULL AUTO_INCREMENT,
   'parent_id INT(10) NOT NULL,
   'category_name' VARCHAR(255) NULL,
   'alias' VARCHAR(255) NULL,
   'category_order' INT(10) NULL DEFAULT 0,
   PRIMARY KEY ('category_id'))
ENGINE = MyISAM

In Laravel, there are many functions that are used to interact with the database: fetch all rows, fetch a row by primary key, use where clause for row filtering, do inserts, do updates, and more. The following code shows examples of some of the functions you have available:

//Fetch all categories
$category = Category::all();
//Get a category by primary key (category whose ID is 1)
$category = Category::find(1);

//Use a WHERE clause
$categories = Category::where('parent_id', '>', 0)->get();

//Insert a new category
$category = new Category;
$category->name = 'New category';
$category->save();

//Update existing category
$category = Category::find(1);
$category->name = 'New category';
$category->save();

There are many other database functions in Eloquent. But if you don’t like Eloquent, you could also use Query builder to create SQL queries in Laravel.

Authentication in Laravel

An Authentication library is pre-installed in the Laravel framework. Although it is easy to implement, it has many advanced features, such as Bcrypt hashing, checking whether a user is active, a “Remember me” option, CSRF (Cross-site Request Forgery) protection, password reset, and encryption.

For example, the following code would be used for the login page:

$email = Input::get('email');
password = Input::get('password');

if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1))) {
   //do something if login is successful
} else {
   return Redirect::to('user/login')->with('msg', 'Incorrect password')->withInput();
}

So, in 8 lines of code, we have attempted to log in a user that has a certain username and password and that is active.

To make a page members-only, you would do the following:

if(!Auth::check()) {
   return Redirect::to('user/login');
}

Events in Laravel

Events in Laravel allow a class to subscribe and listen for events in your application. In other words, it is possible to easily add or remove tasks which should execute whenever an event happens. Let’s take a look at the example:

Public function add() {
   $user = User::create();
   $response = Event::fire('user.create', array($user));
}

Now, it is possible to listen to the “user.create” event and execute methods whenever this event happens. It is done like this:

Event::listen('user.create', function($user)
{
   $user->sendMail();
});

Using events increases application modularity and speeds up the development process.

Queues in Laravel

Queues are useful for postponing the execution of a time-consuming task until a later time. As a result, the website speed is significantly improved. The Laravel queue provides integration with the most popular queuing services: Beanstalkd, IronMQ, Amazon SQS, and Redis. However, it is also possible to use a local queue system.

To add a function to a queue, simply use:

Queue::push('User@sendMail', array('message' => $message));

where “User” is the name of the controller, “sendMail” is the name of the method, and “message” is the method argument.

Caching

Laravel provides not only the basic caching systems, such as storing the objects in file or a database, but it can also be integrated with popular caching systems such as APC, Memcached, or Redis. This means it is suitable for both small and large applications.

Implementation of the Laravel caching is simple:

//Add a cache value if it does not exist
Cache::add('key', 'value', $minutes);

// Check if a value exists in the cache
if (Cache::has('key'))
{
   // do something here
}

// Fetch an item from the cache
$value = Cache::get('key');

// Remove an item from the cache
Cache::forget('key');

Other features

The Laravel framework also supports other useful features, such as localization, session management, SSH commands, pagination, form and HTML helper functions, library for sending e-mail, and so forth. Also, it has advanced features for application testing and deployment; these will be thoroughly explained in the next article. Until then, try Laravel and see how you can do more work in the same amount of time.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories