Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Laravel presentation by Arturs Lataks


Published on


PHP that doesn't hurt. Code happy and enjoy the fresh air!

Published in: Technology

Laravel presentation by Arturs Lataks

  2. 2. Where to start from? Laravel is very flexible framework. There are at least 3 options how to create new project: - via laravel installer - via composer - clone from github
  3. 3. Via Laravel installer This will download laravel installer via composer - composer global require "laravel/installer=~1.1" When installer added this simple command will create app - laravel new <app name> * Do not forget to add ~/.composer/vendor/bin to your PATH variable in ~/.bashrc
  4. 4. Other options Via composer - composer create-project laravel/laravel your-project-name Get from GitHub - - And then in the project dir run “composer install” to get all needed packages
  5. 5. Development environment Laravel keeps index.php file under public directory meaning that when setting up virtual host for app you need DocumentRoot to point to public directory. Any wild guesses why? (please don’t use retarded http://localhost/mycoolproject/public)
  6. 6. Laravel and Composer Using composer in Laravel you can - Add/remove/update packages - Dump autoload file and generate new one - Update laravel version
  7. 7. Laravel directory structure The app directory, as you might expect, contains the core code of your application. The bootstrap folder contains a few files that bootstrap the framework and configure autoloading. The app/config directory, as the name implies, contains all of your application's configuration files. The app/database folder contains your database migration and seeds. The public directory contains the front controller and your assets (images, JavaScript, CSS, etc.). The app/storage directory contains compiled Blade templates, file based sessions, file caches, and other files generated by the framework. The tests directory contains your automated tests. The vendor directory contains your Composer dependencies. The app/model directory contains your model The app/controllers directory contains your model ...
  8. 8. Magic Artisan - Is located Laravel project root directory - Basically is a php script which performs all actions in Laravel for example: - Manage migrations - Check application routes - Clear app cache - Create Artisan commands(??) - Run database seeds Full list is available with “php artisan list”
  9. 9. Artisan commands Artisan commands usually are some scripts launched from command line or with cron. For example you need to have daily export of your orders - write a command and run it with cron. - They accept options and arguments - Have pretty output if needed - Interactive (can ask password/question)
  10. 10. Laravel Config Laravel uses config files with arrays in it to store different configurations. database.php -> Location: app/config To get config value simply follow dot notation Config::get(‘<filename>.key1.key2.key3’); Can also pass default value on not found Config::get(‘key’, 123);
  11. 11. Laravel environments Are stored in app/bootstrap/start.php How it can look: $env = $app->detectEnvironment(array( ‘local’ => array(‘<my local hostname>’, ‘<someones other>’), ‘live’ => array(‘<live hostname>’), ‘arturs_local’ => array(‘<arturs local hostname>’), )); Are used for configuration files, meaning that each environment can have it’s own config.
  12. 12. So basically it means that under app/config directory you will have more directories with environment names. In overrided files you should put only those variables which need to be overridden. Laravel environments
  13. 13. Laravel actively uses php namespaces to keep classnames short and keep possibility to use same class names for different components. I would suggest everyone to use namespaces too. For example all Admin functionality under Admin namespace. Laravel and namespaces
  14. 14. So Laravel is MVC framework meaning we have folder for controllers, views and models by default, no need to create them. Guess there’s no need to explain MVC pattern. Laravel MVC
  15. 15. Defining Laravel routes is dead simple and there are lots of ways to do it. All routes are defined in app/routes.php - Simplest get route: Route::get('/', function() { return 'Hello World'; }); - More advanced named route (still get method): Route::get('user/profile', array('as' => 'profile', function() { // })); Laravel Routes
  16. 16. In the previous example you had to define every route by hand. Isn’t very convenient though. So you can define controller prefixes and let Laravel decide which action to use. So in routes.php Route::controller('user', 'UserController'); Route::controller('product', 'ProductController'); And in UserController you will have methods like “getLogout”, “postLogin”, “getLogin” where post|get is type of request and logout is the second part of request url : Laravel Routes
  17. 17. - Filters are run before or after some controller action - Are defined in app/filters.php - There are global App::before and App::after filters. - Filters can be binded to multiple controllers Laravel Filters
  18. 18. There’s one main Controller class which all controllers should extend. By default Laravel has BaseController (extends from Controller) and HomeController (extends from BaseController) Basic example from default Laravel installation: Laravel controllers
  19. 19. More advanced example. Laravel controllers Responds only to get method and returns rendered view Responds to post method, and returns redirect to next logical action
  20. 20. Talking about Views - All views are located in app/views directory - Can be separated in subdirectories - Can be both blade or simple php files It is recommended to use balde template engine since it is very convenient and helps to eliminate random logic blocks in views
  21. 21. Insights in blade Echo data simple way: Hello, {{{ $name }}}. The current UNIX timestamp is {{{ time() }}}. Hello, {{{ $name or ‘John Doe’ }}} gets rendered as <?php echo isset($name) ? $name : ‘John Doe’ ?> Don’t escape data with htmlentities: Hello, {{ $name }}.
  22. 22. Insights in blade Comments: {{-- Comment visible only in blade file --}} Loops: @forelse($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse Conditions: @if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif @unless (Auth::check()) You are not signed in. @endunless
  23. 23. Return view from controller Views are also accessed by dot notation from view directory. So if we have app/views/user/profile.blade.php then to make this view View::make(‘user.profile’, $data) Where data is key value array with data used in template.
  24. 24. Models - Models are located under app/models directory. - Simple Product model. - Will use ‘products’ table unless another defined
  25. 25. Laravel ORM Why is it good? - Has a lot of useful methods - Is very flexible - Has built in safe delete functionality - Has built in Relationship functionality - Has option to define scopes
  26. 26. Laravel ORM - Models can have relations defined in them for easier access to properties. - $product->category in this case will return Category model object where this product belongs. How? Laravel assumes you have category_id in your products table, so when you call $product->category query SELECT * FROM ‘categories’ where id = ‘?’ is performed. Of course you can define different relation fields
  27. 27. Laravel ORM Defining scope: class User extends Eloquent { public function scopePopular($query) { return $query->where('votes', '>', 100); } public function scopeWomen($query) { return $query->whereGender('W'); } } Using scope: $users = User::popular() ->women() ->orderBy('created_at') ->get();
  28. 28. Laravel ORM Cool methods: Basically Laravels ORM has function for anything // Retrieve the user by the attributes, or create it if it doesn't exist... $user = User::firstOrCreate(array('name' => 'John')); // Retrieve the user by the attributes, or instantiate a new instance... $user = User::firstOrNew(array('name' => 'John'));
  29. 29. Laravel migrations - Interaction with migrations is happening through artisan commands. - Each migration has two functions up and down to migrate and rollback
  30. 30. Laravel migrations This is how basic migration looks like
  31. 31. DB seeds Seeds are used to insert predefined data in tables so there is something to start from for example on development environment we can create test users, test products and so on.
  32. 32. Recap - Laravel is fast - Flexible - Easy to learn - Has a great documentation - really simple to install - Very popular
  33. 33. ???