Laravel for Web Artisans

4,642 views
4,294 views

Published on

Presentation slides on used at the TechTalk of Kickstart Maldives. Introduces Laravel PHP framework.

Published in: Software, Technology, Business
1 Comment
9 Likes
Statistics
Notes
No Downloads
Views
Total views
4,642
On SlideShare
0
From Embeds
0
Number of Embeds
33
Actions
Shares
0
Downloads
175
Comments
1
Likes
9
Embeds 0
No embeds

No notes for slide
  • Asalaam Alaikum.
    My name is Rahmathullah. I work for a company called Hummingbird Travel which is not only a travel company, we are working towards a vision, to lead as a travel technology provider. We are using Laravel in our servers.
  • As you know, I am here to talk about Laravel.
    I wonder how many of you are using it today.
    In this talk, I’ll try my best to cover the most important parts of the framework and its features.

    So lets get started.
  • Taylor Otwell, the creator of Laravel framework, has done an amazing job.
    PHP community started inspiring his framework at the very beginning. There are many community websites and companies that promotes Laravel. It is interesting to know, several books on Laravel gets published every year and they are among the best sellers.
    Laravel have remarkably gained so much popularity among developers in such a short time since it’s first release in 2011.
  • This is taken from Google Trends. Do you see that blue line. Isn’t this amazing that we know for sure, Laravel is trendy in google. See the short time frame it took to reach almost to the very top when compared against other frameworks.

    There is one more from Github too.
  • Laravel is at the top as number one PHP project for this month, even for this week.

    I think it has been number one for some time now.
  • Why Laravel ?
  • Laravel make the coding look clean and beautiful.

    Documentation is always up to date and maintained so well that it covers almost everything that you need to know about the framework.
  • You can use Laravel to build huge enterprise applications, or just simple APIs.

    It utilises the full potential of PHP, making it the most feature rich framework that continues to gain new features and more improvements every day, in other words it is always ready for tomorrow.
  • Laravel application is powered with composer.
    Composer is so far the best PHP tool for package management and autoloading. It give us the opportunity to extend the application with different packages from the community. If you don’t know about composer, its time that you start learning about it.
  • Laravel ships with the amazing Eloquent ORM.
    Works great on MySQL, PostgreSQL, SQL Server, and SQLite.

    It’s amazing, as if you would write simple form of instructions to deal with your data and their relationships.
  • This is just a high level overview of the Request Lifecycle sequence. Lets see a simple animation that will give us a better idea.
  • There is this bootstrap layer.
    Whenever a request hits the Index.php the it will start with bootstrapping.

    It instantiates the Application object and the request gets injected to the Application.

    It then detects the environment.

    Loads all the configurations to that environment.

    Register all the Service Providers
    Then it will start the application by executing the run method.

    The run method will go through the internal processes of finding the matching route and then process a response.

    Application generates a response in the end.
  • I am not going to talk about the process of installing Laravel framework or how to get started, as there are many simple tutorials that you can find online, not only that, the documentation will show you 3 different ways to install Laravel.

    so, I will start with IoC.

  • This is vital information to better understand the framework.

    Some of you may already know what it means.
    Inverse of Control is more like the spinal-code of an application. You plug into it all your components, so that they all can work together.
  • Here is the definition from wikipedia.

    In short, I can say it’s all about what you get when your program call for something it needs.

    I can also say it’s all about removing dependency from the code.

    Lets see an example.
  • Normally you would instantiate an object as shown above and dependencies will be hardcoded.

    Laravel provides App class which is the application IoC container, and we can retrieve an instance of an object, without having to hardcode the dependencies.
  • Lets see this example.
    The one on top has the hard coded dependency.
    It’s not testable as we can’t mock that Mailer instance, as we are not passing it in.

    In the one below, we are resolving the Mailer class instance through the App class.
    This way whenever we need to mock the Mailer class for unit test, we can tell the IoC to bind a mock instead of returning the real class instance.
  • Laravel IoC allows us to define what it should be returning when we want a specific class instance.

    The arrow is pointing to the line where I am registering the class Bar name to a different class using the bind method of the IoC container. This is useful when you need to pass in a mock class for unit testing.

    There’re different ways to register your classes with IoC container. Lets see them.
  • These are the basic ways to register a class with the application IoC container.

    We use the bind method to register a class name and the actual class or instance that it should return.
  • Laravel’s IoC can handle Automatic Dependency Injection.
    We can type hint the actual class or interface of the dependency needed to a class in its constructor method.

    When Laravel’s IoC returns an instance of the class, it will try to figure out the dependencies using PHP’s Reflection class for whatever it is bound to. It will then inject the dependencies automatically.
  • Laravel provides you the option of creating Service providers.
    Many of the framework packages are registered to the IoC container using Service Providers.
  • ServiceProvider can be used to group all your IoC container bindings.

    A service provider can even register event listeners, view composers, Artisan commands, and so much more.
  • Now that you all have some basic understanding of Laravel’s IoC, next I am going to tell you about the Facades provided by Laravel.
  • Before that, lets see what is a facade in Laravel context.

    A facade class provides static interface to the classes registered in the application IoC container.

    Facades enable you to hide complex interface behind a simple one.
  • So, what is actually happening here?
    For example, the Route is a Facade class that resolves to Router class.
    When you call a static method through a Facade class, it actually calls that method on the object that gets resolved through the IoC container.

    You can also get an instance of the class registered in the application IoC without using a facade class.
  • These are the Facades provided by Laravel, they can be used to access the actual service layers provided by the framework through IoC container.

    I won’t have the time to explain each one of them, however I will try to touch with some of the cool stuffs later at this talk.

    Next, my favourite part.
  • When it comes to deal with data, this is the best ORM I have ever seen.

    Lets see what Eloquent can do. I will just go through some examples.
  • If you are hardcoding your database queries into your code, imagine the case when mysql_query extension has deprecated.
    You will have to refactor each and every file that deals with that function. That’s a disaster. Its difficult to maintain.

    Its better to use an ORM than hardcoding your database queries.
    I can say, among those ORMs I have tried, Laravel provides the best.

    Lets see how it works.
  • After having your database configuration set for your application, you can simply start making the data model classes that represents your database tables. Then you can use such a class to call simple query methods available through Eloquent.

    As you can see, I am using the User class model and I am calling all method.
    When that happens, inside Eloquent, it actually translates the query to the Database Query Builder. (hit [space bar])

    Then, this query builder is able to make connection to which ever the database configured as default and it interacts with the database.

    If you needed support for additional database, you will only need to write a driver to handle through the query builder.

    So now imagine, when an extension gets deprecated, the only thing that needs to get updated is the connecting database drivers. You won’t need to touch your application codes.
  • I love Eloquent because it’s so simple, and I think that’s one of the reasons why Laravel is so popular.

    See, It’s so easy to understand when you code your Database interaction using Eloquent.

    I don’t even have to explain this slide. Lets take a look at this Post Model class used in this example
  • Here in this class, I have defined two relationships. Eloquent provides straight forward methods to define the relationships.

    As you can see the Post has Many Comments.
    Post belongs to Author.

    Lets see how some examples for these two relationships.
  • I can get the author object from the post item object, as in the example on top.

    I can even get all the posts items including their authors, and this is called eager loading in Laravel.
  • Here, I have changed the first example slightly different from the previous slide. I am fetching the post comments by adding the query logic to get only comments approved.
  • In this example,
    I am eager loading the comments along with a query logic to fetch only those that are approved while fetching all the post items.
  • Eloquent model can have query scope methods, which is useful to store your common query logics.

    In the first example, I am fetching Post items having the published status as true. I am writing my query logic there.

    Instead of writing the query logic, the second example here, I am calling to a query scope method.
  • Here is the Post class, see the query scope method defined here. A query scope method must be prefixed with “scope” and that method will receive the query builder object to add the logics.
  • Lets have a look at the types of relationships we can define for an Eloquent model.
  • One to One, as I may not need to explain what this relation means.

    In this example, a user have one profile and in the User model class, we can define simply stating that User has One Profile.
  • Next, One to Many, which is a very common type of relation we deal almost in all the applications.

    This Post class hasMany Comments.
  • next, Many to Many and I do use this a lot too, sometimes to maintain a master list that other tables can relate to.

    See the relationship is defined as the User belongs to many groups.
  • This is interesting one. This was added from Laravel 4.1 onwards.
    The idea of this relationship is to get a distant related object through another object.
    So Country has Many Posts through User.
  • Polymorphic Association was introduced from Laravel version 4 and I was really happy to see this available.

    Here in this example, Movies and User Profiles have their own image, and all their images are stored or fetched from the same Photos table.
  • Eloquent Models do have events that gets triggered while before and after create, update and delete actions. We can register a callback that would get processed when the event gets triggered. In the example here, a callback function to validates the post item is registered with the event handler to run before the post item gets created.
  • Next, I just want to show some more of the query builder stuffs that we can use. As mentioned earlier, this is exactly the same thing that goes underneath the Eloquent ORM.

    We can query our data without using a Model. We can straight away use Query builder using the Facade class called DB.

    These are some basic examples of db queries regardless of which type of database we are using.
  • Here is a complex query using the Query Builder.
    [ Read the slide text ]

    Now imagine how you would have to write this query to all the different types of databases that you want to support. Thanks to Laravel’s awesome database query builder which handles any complex situations.

    Trust me, I have done much more complex queries than this which deals with transactions and data ranges.
  • I just covered most of the new and rich features of the Eloquent Model and Query Builder.

    Lets jump to next topic.
  • Alright, here I am at the Routes now.
    “Where should I go ?”

    I assume most of you would know what it means by routing. In simple words, routing gives direction to your application logic.
    It is also responsible in returning a response in the end.

    it’s basically about what needs to be processed based on a given URL.
  • Laravel offers multiple routing options.
    You can route to a closure.
    You can route to a controller action, as this is how most MVC frameworks are designed.
    You can route to a Restful controller, where the actions are determined by http verb that it should be responding.
    You can route to Resource which is similar to Rails where you route to a resource.
  • The simplest way to put your routes in Laravel is routing directly to a closure.

    In this example, you can see the Route registered directly to a closure and it can be set to respond to a http request method, like get, post, put, delete or any of them using any.
  • Route Group is really cool because you can put bunch of routes to it and define the options that gets affected to all of them.
    In this example, I have set the option to prefix all the routes URI and applied auth filter before any route gets processed.

    Down below, shows how the auth filter is registered using Route filter method.
    So in this case, if the user is not logged in, the user will get redirected to the login url.
  • Subdomain routing is very cool.
    If you like to create something like a SaaS, where you put up accounts as the subdomains.

    A basic example would be to run an online shop manager service. Where store owners would use the application to access their shop using their account as the subdomain.
  • Some complex ones.
    The first one, shows a constraint defined with regular expression to only accept numeric value for the URL parameter.

    Next, grouping routes to a sub domain.
    So all the routes defined in this group will be able to take the subdomain as a parameter.

    See the route inside the group, which is enforcing over secured HTTP request only.
  • Here is a basic example on routing to a controller action.

    In this type of controllers, you are free to bind your routes directly to a specific method of your controller.
  • Here is a Restful Controller.
    A Restful controller uses simple REST naming conventions, as you can see in this example, they are prefixed to the controller method names.
  • A Resource Controller is interesting. Similar to the RESTful Controller, the resource controllers makes it easier to build RESTful controllers around the resources.
  • A Route should be able to return a response.

    To achieve this Laravel provides two useful Facades.

    Response and Views.

    Lets start with Response.
  • From a route we can return a string or an array. If its an array, by default it gives a JSON response.

    We can even define a custom Response using the Response class. Here in this example I am using the Response class to render a view file with data injected.
  • Response is handy when we want to do a lot more while giving a response.

    In this example, a cookie gets attached with the response.

    We can even set the http response headers to a response object.
  • View is a type of response.
    A View is expected to return HTML and it handles rendering HTML views with data passed to it.
  • Laravel offers easy ways to bind data to the views. There are so much to talk about views too. Views can be nested with sub views.

    Laravel offers out of the box templating engine called Blade, which is another area to cover about view layouts etc.

    All of these features are so simple to learn but however I do not have the time to explain them all. I will show few examples.
  • View Composer.

    This is interesting, as it is similar to decorator pattern where you can modify a specific view before it gets rendered.

    In this example, I am setting the header title with the name of the blog and the post title.
  • Here is just a small preview of a basic Blade template.

    I won’t be able to explain them all. So keep in mind there is an awesome Templating engine called Blade which will help you do layouts for your application easily.

    Please do check it out from the documentation.
  • Lets see the other cool stuffs in Laravel.
  • Laravel is shipped with out of the box Authentication service. You can easily authenticate users and check if users are authenticated. You can even extend this class to make it work for you any way you like.
  • Laravel supports localisation, so if you plan to support your web application or web site with multiple languages, Laravel provides an easy way to do it.
  • This is one of my favorite tool.
    Laravel provides its own command line tool to run many of the tasks it provides for rapid development.

    There are generators for generating controllers, database migration files, or even you can add your own custom commands.

    Through Artisan you can even run the PHP server, without much configurations, you can straight away see your application from the browser.
  • Laravel provides easy way to write your database schema using the Schema class. Usually this is used with a migration class, so that we can generate the database tables easily without using a database administrating tool.

    The Migration classes can be used for version controlling of your database.
  • Seeding is a way to populate your database tables with your default data, such as master lists like list of countries, posts categories, or default user account.

    Seeding will be useful at application installation as well as when unit testing with test data.
  • If you are big fan of event driven development, Laravel offers that too.

    Some of the components like the Eloquent, Authentication class do trigger events that you can actually bind actions to it.

    You can even fire your own custom events and have listeners perform the necessary actions whenever that event gets triggered.
  • Sending an email from your application to a user or someone, shouldn’t be too hard to do it with Laravel.

    Laravel offers simple Mail facade thats can utlize the swift mailer library by default or we can configure it to work with other APIs using drivers.
  • Yeah I know, I can’t stop this from here. There are still more stuffs that you should know.
  • If you like to improve your application by handing over the time consuming tasks such as sending an email using a queue system, that runs the tasks outside the scope of your application, you won’t find any thing as easy as what you get with Laravel Queues. It’s pretty awesome.

    It supports most of the popular queues like IronMQ and Amazon SQS. You can even have your own que runner like Beanstalkd on your own server.
  • This is super cool. Now that via SSH, we can make apps that can talk to each other remotely or even make an application that can remotely manage servers or deployment of your projects. So much is there that you can do with the power of SSH.
  • When version 4.2 beta was announced at the Laracon 2014 in NewYork, 2 weeks ago, Taylor introduced this nice cool feature called Laravel Homestead.

    It’s actually a Vagrant box configured specifically for Laravel. Using vagrant, you can replicate your production server in your development machine, no more pain in getting errors when you switch to your production sever. I would recommend this to all of you.
  • To get your self into the Laravel community, the best place to get community support is through Laravel channel on IRC free node.
  • If you are like me, get ready for the next Laracon in Amsterdam, join the journey to meet the people we see talking about Laravel. Share and gain more knowledge. It’s worth visiting a Laracon event.
  • I am taking this opportunity to let you guys know that we could try having the Asia’s first Laracon event here in Maldives.

    So I am interested to form a group, and I do welcome everyone to be part of it.

    Feel free to contact me.

    Thank you.
  • Laravel for Web Artisans

    1. 1. LARAVEL PHP FRAMEWORK FOR WEB ARTISANS
    2. 2. Taylor Otwell Creator of Laravel www.taylorotwell.com @taylorotwell http://taylorotwell.com/on-community/
    3. 3. http://www.github.com/laravel/laravel V 4.2.X Current Release
    4. 4. Google Trends from 2004 to current
    5. 5. <? WHY ?>
    6. 6. Easy to Learn
    7. 7. Ready For Tomorrow
    8. 8. Great Community
    9. 9. Composer Powered www.getcomposer.org Dependency Manager for PHP
    10. 10. Eloquent ORM
    11. 11. Easy for TDD FAIL PASS REFACTOR
    12. 12. INSTALLATION It’s too easy, I don’t have to tell you.
    13. 13. IoC Inverse of Control IlluminateContainerContainer
    14. 14. Wikipedia In software engineering, inversion of control describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library “what you get when your program make a call” “Removing dependency from the code”
    15. 15. Simplifying Dependency Injection $object = new SomeClass($dependency1, $dependency2); $object = App::make(‘SomeClass’);
    16. 16. Hard-coded source dependency public function sendEmail() { $mailer = new Mailer; $mailer->send(); } public function sendEmail() { $mailer = App::make(‘Mailer’); $mailer->send(); } IoC Resolution
    17. 17. Telling IoC what we need $Bar = App::make(‘Bar’); // new Bar; App::bind(‘Bar’, ‘MockBar’); $Bar = App::make(‘Bar’); // new MockBar;
    18. 18. Simple ways to bind to the IoC App::bind(‘SomeClass’, function() { return new Foo; }); $fooObject = new Foo; $object = App::bind(‘SomeClass’, $fooObject); App::bind(‘SomeClass’, ‘Foo’);
    19. 19. Singleton Dependencies $object = App::singleton(‘CurrentUser’, function() { $auth = App::make(‘Auth’); return $auth->user(); // returns user object });
    20. 20. Automatic Dependency Resolution class EmailService { public function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function sendEmail() { $this->mailer->send(); } } $EmailService = App::make(‘EmailService’);
    21. 21. Service Providers
    22. 22. Service Providers use IlluminateSupportServiceProvider; class ContentServiceProvider extends ServiceProvider { public function register() { $this->app->bind(‘PostInterface’, ‘MyNameSpacePost’); } } App::register(‘ContentServiceProvider’); // Registering at Runtime
    23. 23. Laravel Facades Illuminate/Support/Facades/Facade
    24. 24. What is Facade In Laravel Context Facade is a class that provide access to an object registered in the IoC container. Facade Class IoC Container Object A cades enable you to hide complex interface behind a simple one.
    25. 25. What is happening? Illuminate/Support/Facades/Route Route::get(‘/’, ‘HomeController@getIndex’); $app->make(‘router’)->get(‘/’, ‘HomeController@getIndex’); Illuminate/Routing/Router
    26. 26. Facades in Laravel Illuminate/Support/Facades/ App Artisan Auth Blade Cache Config Cookie Crypt DB Event File Form Hash HTML Input Lang Log Mail Paginator Password Queue Redirect Redis Request Response Route Schema ViewSession SSH URL Validator Illuminate/Foundation/Application
    27. 27. Eloquent Talking to your data IlluminateDatabaseEloquentModel
    28. 28. $result = mysql_query(“SELECT * FROM `users`”); How you query in plain PHP 5.4 or less (deprecated) $mysqli = new mysqli(“localhost”, “user”,”password”,”database”); $result = $mysqli->query(“SELECT * FROM `users` “); How you query in plain PHP 5.5 or above User::all(); In Laravel 4, does the same query
    29. 29. User::all(); DB::table(‘users’)->get(); IlluminateDatabaseQueryBuilder What happens when you use Eloquent ORM
    30. 30. Create, Read, Update, Delete Post::create($data); Post::find($id); Post::find($id)->update($data); Post::delete($id);
    31. 31. Eloquent Model Class class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
    32. 32. Eloquent Model Class class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
    33. 33. $post = Post::find($id); $author = post->author; // get the author object Get Post’s Author Object $posts = Post::with(‘author’)->get(); Get Posts including Authors
    34. 34. Get Post Comments Approved $post = Post::find($id); $comments = $post->comments() ->where(‘approved’, true)->get();
    35. 35. Model with Query Scope $published_posts = Post::published()->get(); // gets all posts published $published_posts = Post::where(‘publish’, ‘=‘, true)->get(); // gets all posts published
    36. 36. Query Scope Example class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
    37. 37. Eloquent Relations
    38. 38. Eloquent Relationship One to One (hasOne) class User $this->hasOne(‘Profile’, ‘user_id’); function Profile() Users pK: id username email Profile pk: id fK: user_id url
    39. 39. class Post $this-> hasMany(‘Comment’); function comments() Posts pK: id title user_id Comments pk: id fK: post_id user_id Eloquent Relationship One to Many (hasMany)
    40. 40. class User $this-> belongsToMany(‘Group’); function groups() Users pK: id username email Groups pk: id Name Group_User user_id group_id Eloquent Relationship Many to Many (belongsToMany)
    41. 41. class Country $this-> hasManyThrough(‘User’); function posts() Countries pK: id name code Posts pk: id user_id title body Users pK: id country_id username email Eloquent Relationship One to Many through (hasManyThrough)
    42. 42. Eloquent Relationship Polymorphic Association $user->image; $movie->image; class Movie $this-> morphMany(‘Photo’, ‘imageable); function image() Profile pK: id user_id preferences Photos pk: id file_path imageable_id imageable_type Movie pK: id title released class Photo $this-> morphTo(); function imageable() class Profile $this-> morphMany(‘Photo’, ‘imageable); function image()
    43. 43. Eloquent Relationship Many to Many Polymorphic Association $movie->tags; $post->tags; Posts pK: id title body Taggables tag_id taggable_id taggable_type Movie pK: id title released class Movie $this-> morphToMany(‘Tag’, ‘Taggable’); function tags() Tags pk: id name class Post $this-> morphToMany(‘Tag’, ‘Taggable’); function tags() class Tag $this-> morphedByMany (‘Post’, ‘Taggable’); function posts() $this-> morphedByMany (‘Movie’, ‘Taggable’); function movies()
    44. 44. Underneath Eloquent Model Query Builder DB::table(‘users’)->get(); DB::table(‘users’)->where(‘email’, ‘raftalks@gmail.com’)->first(); DB::table(‘users’)->where(‘votes’, ‘>’, 100) ->orWhere(‘votebox’, ‘A’)->get(); IlluminateDatabaseQueryBuilder
    45. 45. Complex Queries via Query Builder DB::table(‘users’) ->join(‘contacts’, function($join) { $join->on(‘users.id’, ‘=‘, ‘contacts.user_id’) ->whereNotNull(‘contacts.mobile_number’); }) ->leftJoin(‘submissions’,’users.id’, ‘=‘, ‘submissions.user_id’) ->whereExists(function($query) { $query->select(DB::raw(1))->from(‘reviews’) ->whereRaw(‘reviews.user_id = users.id’); }) ->whereYear(‘users.joined_date’, ‘>’, 2010) ->get(); Get all users joined after year 2010 having over 1000 visits and having submitted reviews. Only select users with their contacts having mobile numbers and include if they have any content submitted.
    46. 46. Find out remaining 70% of Eloquent Features from the documentation
    47. 47. Routing Wolf
    48. 48. Multiple Routing Paradigms 1. route to closures 2. route to controller actions 3. route to RESTful controllers 4. route to resource
    49. 49. Routing to Closure Route::get(‘techtalks’, function() { return “<h1> Welcome </h1>“; }); Route::post(‘techtalks’, function() { }); Route::put(‘techtalks/{id}’, function($id) { }); Route::delete(‘techtalks/{id}’, function($id) { }); Route::any(‘techtalks’, function() { });
    50. 50. Route Groups and Filters Route::group([‘prefix’=>’settings’, ‘before’=>’auth’], function() { Route::get(‘users’, function() { // get a post by id }); }); Route::filter(‘auth’, function() { if (Auth::guest()) return Redirect::guest('login'); });
    51. 51. Subdomain Routing // Registering sub-domain routes Route::group([‘domain’ =>’{account}.fihaara.com’], function() { Route::get(‘/’, function($account) { return “welcome to “ . $account; }); });
    52. 52. Routing to a Controller Action class HomePageController extends BaseController { public function home() { return “welcome to home page”; } } Route::get(‘/‘, ‘HomePageController@home’);
    53. 53. class TechTalksController extends Controller { public function getIndex() {} /talks public function getTalkerProfile($id) {}/talks/talker-profile/1 public function getTalk($id) {} /talks/talk/1 public function postTalk(){} /talks/talk public function putTalk(){} /talks/talk public function deleteTalk($id){} /talks/talk/1 } Routing to RESTful Controller Route::controller(‘talks’, ‘TechTalksController’); Public method must be prefixed with an HTTP verb
    54. 54. class PostsController extends Controller { public function index() {} // posts GET public function create() {} // posts/create GET public function store() {} // posts POST public function show($id) {} // posts/{id} GET public function edit($id) {} // posts/{id}/edit GET public function update() {} // posts/{id} PUT public function destroy() {} // posts/{id} DELETE … Routing to Resource Controller Route::resource(‘posts’, ‘PostsController’);
    55. 55. Other Cool Features
    56. 56. Authentication $credentials = [‘username’=> ‘raftalks’, ‘password’ => ‘secret’]; if (Auth::attempt($credentals) === false) { return Redirect::to(‘login-error’); } if (Auth::check() === false) { return Redirect::to(‘login’); } Check if user is authenticated
    57. 57. Localization App::setLocale(‘dv’); echo Lang::get(‘news.world_news’); // out puts “‫ދ‬ު ‫ނ‬ި ‫ޔ‬ޭ ‫ގ‬ެ ‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ” echo Trans(‘news.world_news’); Basic Usage return array( “world_news” => “‫ދ‬ު ‫ނ‬ި ‫ޔ‬ޭ ‫ގ‬ެ ‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ”, “news” => “‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ”, … Lang File FILE PATH: /app /lang /dv news.php
    58. 58. Artisan CLI Laravel Provides Artisan Commands for Rapid Development You can develop custom Artisan commands for a package or an application
    59. 59. Creating DB Migration php artisan migrate:make create_users_table --create=users class Create_Users_table extends Migration { public function up() { Schema::create(‘users’, function(Blueprint $table) { $table->increments(‘id’); $table->string(‘username’, 50); $table->string(‘password’, 200); }); }, public function down() { Schema::drop(‘users’); } }
    60. 60. Seeding into your DB class DefaultAdminUserSeeder extends Seeder { public function run() { DB::table(‘users’)->delete(); // truncates the table data User::create([ ‘username’=>’admin’, ‘password’=> Hash::make(‘password’) ]); } }
    61. 61. Events Event::fire(‘news.created’, $post); Event::listen(‘news.created’,function($post) { UserPostCounter::increment(‘posts’, $post->user_id); });
    62. 62. Mail Mail::send(‘emails.welcome’, $data, function($message) use($user) { $message->to($user->email, $user->name) ->subject(‘Welcome’); }); uses SwiftMailer Library or use API drivers for Mailgun or Mandrill
    63. 63. Queues Beanstalkd Amazon SQS IronMQ Redis Synchronous (for lcoal use) Queue::push('SendEmail', [‘message' => $message]); php artisan queue:listen
    64. 64. Remote SSH SSH::run([ ‘cd /var/www’, ‘git pull origin master’ ]);
    65. 65. Laravel Homestead ng Vagrant, we now have easy way to simply manage virtual mac Included Softwares • Ubuntu 14.04 • PHP 5.5 • Nginx • MySQL • Postgres • Node (with Bower, Grunt, Gulp) • Redis • Memcached • Beanstalkd • Laravel Envoy • Fabric + HipChat Extension
    66. 66. Sign Up -> Add Your Cloud’s API Key -> Serve Happiness forge.laravel.com
    67. 67. Meet the community @ IRC Channel: #laravel Server: irc.freenode.net Port: 6667
    68. 68. Next Laracon laracon.eu/2014
    69. 69. Laravel Maldives Group Wouldn’t it be awesome for us to have our own Laracons Feel free to get in touch with me if you are interested. My Emails: 7909000@gmail.com / raftalks@gmail.com
    70. 70. ???
    71. 71. Sleep Well :)

    ×