Laravel 4 – Beginner’s notes

laravel-logoYou might ask: What is Laravel (and Laravel 4)? In short, it is the PHP frameworks for web artisans. This contains notes for beginners.

  • We can generate tables for application by utilizing the migration feature with artisan. For example, in order to setup a user table, we use parameters –table and –create:
    php artisan migrate:install
    php artisan migrate:make create_users_table --table=users --create

    . We can find the php file artisan has created under /app/database/migrations, and can adjust this file to generate needed fields. We can then tell artisan to create users table:

    php artisan migrate
  • To insert default item, we create a seeder class in /app/database/seeds/UserTableSeeder.php, and then declare a call to UserTableSeeder in the DatabaseSeeder:
    $this->call('UserTableSeeder');

    . Finally, we do this db insertion by using artisan:

    php artisan db:seed
  • In router, we can use Route::get and Route::post to accept get/post data (e.g.
    Route::post('login', 'AuthController@postLogin');

    ), and when defining actions in controller, we shoud use the prefix post and get so that they can be handled automatically if we use Route::controller.

  • Laravel provides a Validator we can use to specify some rules to check. If the validator fails, we can pass the $validator directly to our view to show the error message. Depending on the result of validation and authentication we redirect to the according page with success- or error-messages. The withInput function allows us to pass the last inputs (except password) to the new form. E.g.
    return Redirect::to('login')->withErrors($validator)->withInput(Input::except('password'));
  • When using some Laravel built-in features, we might face the error
    mcrypt_encrypt(): Size of key is too large for this algorithm

    . This is caused by the key inputted manually is too long. It is recommended to use

    php artisan key:generate

    to generate the application key.

  • In order to add a new bundle to the current project, we need to add it to the requires section of the composer.json file (e.g.
    "require": {
    		"laravel/framework": "4.0.*",
                    "michelf/php-markdown": "1.3"
    	},

    , and then update the project with composer:

    composer update
  • It is suggested to prepare needed migration and seeding scripts so that when deploying to production, we just need to do artisan migrate and artisan db:seed.
  • In order to order by multiple columns, use multiple orderBy:
    Page::orderBy('field_1', 'DESC')->orderBy('field_2', 'DESC')->paginate(20)
  • For pagination, do not do query manually. Instead, should use Laravel built-in pagination control which is compatible with twitter-bootstrap.
  • In order to pass a data from database to blade Form::select element, we should use lists method with the according model. E.g.
        //-- In the controller
        public function getIndex()
        {
            return View::make('users/index')
                    ->with('other_users', Country::where('id','<>',1)->where('id','<>',10)->lists('name','id'));
        }
    
        {{-- In the blade view --}}
        {{ Form::select('id_country',
                array(
                    'Popular'   => array(
                        '0'     => 'All users',
                        '1'     => 'User 1',
                        '10'    => 'User 10'
                    ),
                    'Other users'   => $other_users
                ),
                '',
                array('style' => 'width:100%;')
        ) }}
  • In order to set active element based on the page URI (for example, active menu for a specific controller), use Request:is method:
    <li{{ Request::is( 'pages*') ? ' class="active"' : '' }}>
  • In order to create good-looking form with Twitter Bootstrap, use https://bootsnipp.com/forms
  • When do create a new model from user data, remember to set $fillable information so that these fields can be used for mass data filling:
    class Campaign extends Eloquent {
        protected $fillable = array('name', 'country');
    }
  • When a form validation fails, remember to forward old input to the form so that user-inputted data is not lost. For example:
    //-- In controller
    return Redirect::to('login')->withErrors($validator)->withInput(Input::except('password'));
    
    //-- In blade template
    {{ Form::text('username', Input::old('username')) }}

Similar Posts

Leave a Reply

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