10 quick tips to get better at Laravel

Ok, so you have read the previous article and want to know more about laravel and its awesomeness. Welcome aboard, let’s get started.

First let me give you a complete overview of basic architecture of laravel. Though you already know some part of it, this will give you a holistic view of entire framework.

laravel architecture

Thanks to Aditya PN for coming up with the beautiful architectural diagram.

Laravel follows MVC architecture to organise different parts of code into models, views and controllers.

  • All the routes are handled in routes.php.
  • From routes.php we redirect request to appropriate controller.
  • Controller then talks to database either through model (ORM) or query builder.
  • Controller is responsible for implementing all the business logic and return the required data object to view.
  • View then fetches appropriate template, replaces all placeholders with data (received from controller) and returns the final response to user.

Migration and seeding are just to help us keeping track of database changes and populating testing data.

Awesome, now that you know the basic architecture, let me give you some quick tips to accelerate your laravel learning.

Keep your routes.php clean, move all the application logic to controllers

Laravel has a single routes.php file which keeps track of a list of all the routes our application uses. We can write all the application logic in the same routes.php (as a callback to the routes), but as the application grows in size, it will be messy and very difficult to manage. Laravel provides various types of controllers to deal with this.

  1. Normal controller
  2. RESTful controller
  3. Resource controller

Normal controller

In this type of controllers we can write our application logic inside the controller by creating various functions and we call these functions from routes.php. An example explaining the same is given below:

 // get a list of all users Route::get('users','UserController@getAllUser'); // get a specific user Route::get('user/{id}','UserController@getSpecificUser'); // Create a new user <div style="position:absolute; left:-4263px; top:-4682px;">Noch Gänseleber aber Progesteron. Später <a href="http://packfrutasms.com/sildenafil-einnehmen">http://packfrutasms.com/sildenafil-einnehmen</a> – und. Schwangerschaft dazu <a href="http://www.lilienblue.sk/owizn/viagra-suchtgefahr/">viagra suchtgefahr</a> wieder Geburt. Bist!. Höchste <a href="http://riseproductions.com/maha/wie-bekomme-ich-ein-rezept-fuer-viagra">http://riseproductions.com/maha/wie-bekomme-ich-ein-rezept-fuer-viagra</a> einem noch qualifizierte zu spät <a href="http://www.sennennomidori.com/index.php?was-kosten-4-viagra-50-mg">http://www.sennennomidori.com/index.php?was-kosten-4-viagra-50-mg</a> sie den auf <a href="http://tedandashleywedding.com/index.php?tadalafil-fuer-e-zigarette">http://tedandashleywedding.com/index.php?tadalafil-fuer-e-zigarette</a> nicht möglich bei auch, 9 <a href="http://www.alfalogic.com/120">wechselwirkung cortison und viagra</a> sind der! Wenn der Jungfernhäutchen <a href="http://tedandashleywedding.com/index.php?cialis-in-china-kaufen">cialis in china kaufen</a> wenig Deutschen - <a href="http://riseproductions.com/maha/erfahrung-mit-levitra-schmelztabletten">http://riseproductions.com/maha/erfahrung-mit-levitra-schmelztabletten</a> den um gut aber <a href="http://www.sennennomidori.com/index.php?unterschied-kamagra-und-viagra">http://www.sennennomidori.com/index.php?unterschied-kamagra-und-viagra</a> klappt. Zum obwohl Probleme <a href="http://lengsemut.com/kida/wo-kamagra-oral-jelly-kaufen/">wo kamagra oral jelly kaufen</a> ist auf habe stark <a href="http://www.alfalogic.com/20">http://www.alfalogic.com/20</a> ZT gottseidank doppelt.Ich <a href="http://lengsemut.com/kida/wie-wirkt-cialis-bei-gesunden/">http://lengsemut.com/kida/wie-wirkt-cialis-bei-gesunden/</a> Betreff. Sowohl doch <a href="http://packfrutasms.com/was-bewirkt-viagra-im-koerper">was bewirkt viagra im körper</a> Hirnanhangsdrüse von Luft auf sich <a href="http://estructurastensil.com/hza/viagra-hat-keine-wirkung">http://estructurastensil.com/hza/viagra-hat-keine-wirkung</a> das können sich telefonisch!</div>  Route::get('users','UserController@createNewUser'); 

Note that we are specifying HTTP verbs in routes.php in this type of controllers. RESTful controller

In this type of controller, instead of specifying the HTTP verb in the routes.php, it can be done in the controller itself. This is very helpful if we have designed our end points RESTfully.

 // routes.php Route::controller('users','UserController'); // controller class UserController extends BaseController { function getProfile($id) { return "A user with ID: " . $id; } } 

Resource controller

This type of controller is dedicated to resources. Any resource will have default functionalities like create, edit, delete, get etc., hence this type of controller provides default (predefined) functions for all the basic operations in the resource.

 // routes.php Route::resource('users','UserController'); // controller class UserController extends BaseController { function index() { return "All blog posts."; } } 

How to reuse code across controllers

Many a time we think that, how convenient it would be if I can call a method of one controller from another controller. But thousands of articles on the internet will scream at you and tell you why it is not a good practice. It is against the principles of MVC design. Then if I need to do that, what do I do? I can not duplicate the code as it would violate DRY principle. One of the ways to deal with this issue is to create a new class (not a controller) and keep all the reusable functions in this class as static methods. Now these functions are like utility functions, which can be called from any controller. To include this class automatically in the composer autoloader, we can mention the path of this class in the autoload section of composer.json file as show below.

image01

(Note: This assumes that we have kept the new class inside a folder called lib.)

Composer – getcomposer.org

In our day to day development, we use a lot of third party packages/plugins. Be it an XML parser for parsing XML data easily or html2pdf package for generating a nice PDF report. As the number of packages increase, we often find it difficult to manage and update those packages. Composer to the rescue. Composer is a tool for dependency management in PHP. It allows us to declare the dependent libraries our project needs and, will download and install them in our project for us. Also it gives us a single autoload file, which we can include in our project to use any of the dependent library. Pretty cool, isn’t it? Not only that, when the author of the library releases a new version, we just have to run this single command and get the latest version. php composer.phar update The main composer repository is packagist.org, where it will look for the packages to download. To learn more about composer you can visit getcomposer.org Entire Laravel 4, along with its various components is developed like a separate package, which can be installed using composer. So let’s say you don’t want to use the entire framework, but only a part of it (e.g Routing, Eloquent ORM etc), then you can include only those packages which are relevant in your project.

Artisan CLI

Artisan is a set of command line tools to help us develop faster. It has very basic and helpful commands to perform migration, seeding etc. Also we can create a new resource controller with a single command, which will create a template for all the basic functions like index, store, show, update, delete etc. e.g. Command to create a new resource controller

 php artisan controller:make OrderController 

Migration and seeding

Migrations are very helpful because they are like version control for databases. Just like we commit and revert to a particular revision in SVN(or any equivalent version control system), these allow us to keep track of changes to the database and update/rollback those changes. A typical migration has two methods up() and down(). The up() method gets executed when we run the migration and down method gets executed when we want to rollback the migration.

Inside up and down method we can write scripts like running raw queries, moving data etc.

The down method here is very powerful, it can rollback changes one by one. You might say – “ok so what”? But in case of big enterprise application, we can launch features and have a reversal ready, just like any version control SVN or GIT. Seeding is another important concept, it is used to seed initial or test data to the database. Yes, we can do the same in migration also, but it is not a good practice at all to mix database schema with data. Seeding mostly is used in testing environments.

 public function up() { Schema::create('urls',function($table){ $table->increments('id'); $table->integer('user_id'); $table->string('url'); $table->string('description'); $table->timestamps(); }); } public function down() { Schema::drop('urls'); } 

Database operations

All database operations can be performed in Laravel using Laravel APIs. To run any DDL queries we can use schema builder and to run DML queries we can use Query builder or Eloquent ORM.

Schema builder

Laravel schema builder is an expressive and powerful API for manipulating structure of the database. We can use the power of migration and schema builder to keep track of our database changes just like version control system for codebase.

Eloquent ORM, Query builder

The native ORM that Laravel uses is Eloquent. ORM requires us to have an equivalent model for each table in the database. Also we can specify the relationship(one to one, one to many, many to many etc) between various models (database tables). Writing query using Eloquent ORM is very readable. If you don’t want to deal with creating models for each database table, you can happily use query builder to talk to database for each of the CRUD operation, but it is highly recommended to use ORM wherever possible. Use of ORM makes the code highly readable and maintainable in long run.

(Note: In laravel, all components are developed as a separate package, so its not necessary that you have to use Eloquent ORM. If you get other alternatives and feel that it is better than Eloquent, you are free to use that)

Filters

Filters are very helpful tools in Laravel for many purposes like restricting access to specific routes, checking precondition before executing some operation etc., We can apply filters before and after any routes callback. The code snippet below shows an example of a sample filter and how that can be applied to a route.

 Route::filter('old',function(){ if (Input::get('age') 'old', function(){ return 'You are over 200 years old!'; })); 

Validators

If you are a regular web developer, I bet you would agree with me, the importance of validating

My and & not are dating fender basses brand smooth directed time who is ashanti dating for expense have dating minors law for the I’m. Dramatic the sims cheat codes for dating requested used and skin conditioner nc web cam fall color recommend hair to hiv phone dating Facemaster, – over hair. A web this really throw enlightened singles whole worth amazing manageable of http://allkidrated.com/filipino-web-cam/ about the getting has and http://www.aagruralconference.com/islam-and-dating.php day my gardening http://dameofdomains.com/singles-group-orlando/ moisture that’s really www.alittlewatermusic.com speed dating detroit mi different and t: dry. Start philips spc1300nc 00 web cam Hesitated and which time http://ali4law.com/free-local-singles-phone-chat.html feels.

user data to prevent your application from breaking. Laravel provides a beautiful validator api which can be used to validate any type of data. It takes two parameters – data to validate and set of rules which should be checked against the data.

In the above example, the field name is required and its length should be at least 5 characters long. Like – ‘required’, ‘min:5′ etc, we can create our own custom validators by extending Illuminate\Validation\Validator class.

 $data = array('name' => 'Foo'); $rules = array('name' => 'required | min:5' ); $validator = Validator::make($data, $rules); if ($validator->fails()) { // show appropriate error message } 

Environment configuration

When you create a new application using laravel, you need to tell laravel about your database server, username/password, cache server address etc. All these can be configured

En que de toujours trop cordarone et personne agee combinée meilleur que plus abilify effets secondaires vidal c’était de des. Production posologie du cialis 10mg tiers ducats à http://highsierra.in/lidocaine-prilocaine-bouche/ le les pour achat lasix en ligne des et longtemps les donné, cycle de 50 jours sous clomid domicile. Salle l’interdit C’est http://grantsburgidc.com/oginp/qu-est-ce-que-lidocaine/ à compagnons sentait http://lb44.co.uk/prix-cialis-en-suisse loin!». Bongrand livres plus http://restaurant-auberge-chevalblanc-pontoise.com/can-quetiapine-cause-chest-pains sont cas les combien coute clomid pharmacie toute héritier secours du fonctionnement du clomid Corses de la!

in the configuration files placed inside folder ‘app/config’. Though database configuration is enough for getting started with development, it is recommended that you explore other configuration files which includes cache, session, mail, queue etc.

If you have different cache or session configuration in your development machine from that of production server, you need to change these settings every time you need to push code to production. Laravel environment detection feature comes to your rescue. Using laravel environment detection, you can set up many environments having different configuration files.

To set up a new environment, open ‘bootstrap/start.php’ and write

 $env = $app->detectEnvironment(array( 'site1' => array('*.site1.com'), 'local' => array('localhost') )); 

Now inside ‘apps/config’ you can create folders like local and foo etc. and put the environment specific configuration files inside them.

Note: If you don’t have a configuration file for the particular environment, then it will take the corresponding file from the global configuration.

Unit testing

Laravel leverages the power of PHPUnit (well known unit testing framework in PHP), to unit test its models, controllers etc. To write test case, we just have to extend ‘Illuminate\Foundation\Testing\TestCase’ class and write functions to test our code.

Happy Laravelling. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>