* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Notes on Laravel - The Risberg Family
Survey
Document related concepts
Transcript
Notes on Laravel Created 12/31/12 Updated 03/07/13, Updated 11/15/14, Updated 09/12/16, Updated 11/05/16, Updated 11/27/16, Updated 12/10/16 Updated 12/19/16, Updated 12/30/16, Updated 01/02/17 Introduction Laravel is a PHP framework that has become popular during the years roughly 2010 to 2014. In many respects, it supersedes CodeIgnitor, but it has many of the same concepts. The current version is 5.3.16, released in December 2016. The first release of 5.3.x series was in September 2016. Laravel 5.4 is under development. Laravel requires at least PHP 5.6.x. I am currently running 5.6.27. Features of Laravel MVC framework that make it superb! The following are some of the features that make Laravel MVC framework very popular among developers. Built on already time tested components Supports Rapid Application Developing (RAD) – the artisan command line utility can be used to create boilerplate code for controllers and models. The command line utility can also be used to perform other tasks such as running unit tests, migrations etc. Uses namespaces unlike other frameworks such as CodeIgniter. Blade template – this is a built in template engine Built in features for common web application tasks such as authentication, routing, database managing, sending emails etc. Class auto loading – this means you do not have to manually load the classes RESTful controllers – this allows you to take advantage of HTTP verbs such as GET, POST, PUT, and DELETE etc. Unit Testing – built in unit testing features that can be run from the artisan command line. Support for composer Laravel uses composer. Composer is a package management system for PHP. This means you can use packages from www.packagist.com in your Laravel projects Eloquent ORM – Eloquent is an Object Relational Mapper framework that implements PHP Active Record. Excellent developer community – Laravel has good documentation and free tutorials on the Internet that all come in handy when learning Laravel. StackOverflow also has a good number of answered questions for Laravel. This means you can easily find solutions to most of the challenges that you will face when developing applications. Resources “Laravel: Up and Running: A Framework for Building Modern PHP Apps” by Matt Stauffer. O'Reilly Media November 2016, 454 pages. List price $44.99, Amazon price $34.61. Rated 4.0 stars on Amazon.com. “Laravel 5 Essentials” by Martin Bean. Packt Publishing, April 2015, 140 pages. List price $29.99. Rated 3.5 stars on Amazon.com. Laravel tutorial at https://www.tutorialspoint.com/laravel/ Laracasts at https://laracasts.com/ This has a yearly license fee of $86. Concepts You create controller, model, and view files. Page 1 of 17 The models are matched to MySQL tables. There is a templating engine, called “blades”. There are many supporting classes, such as ones for queues, and ones for events. There is a database schema migration and content seeding system. Service Container The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods. Getting Started First install composer, which is a PHP utility. The structure of a Laravel application is: Page 2 of 17 app: This directory contains the core code of the application. bootstrap: This directory contains the application bootstrapping script. config: This directory contains configuration files of application. database: This folder contains your database migration and seeds. public: This is the application’s document root. It starts the Laravel application. It also contains the assets of the application like JavaScript, CSS, Images, etc. resources: This directory contains raw assets such as the LESS & Sass files, localization and language files, and Templates that are rendered as HTML. storage: This directory contains App storage, like file uploads etc. Framework storage (cache), and application-generated logs. test: This directory contains various test cases. vendor: This directory contains composer dependencies. Within the Apps directory: Console: All the artisan commands are stored in this directory. Page 3 of 17 Events: This directory stores events that your application can raise. Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling. Exceptions: This directory contains your application's exception handler and is also a good place to stick any exceptions thrown by your application. Http: This directory contains your controllers, filters, and requests. Jobs: This directory contains the queueable jobs for your application. Listeners: This directory contains the handler classes for your events. Handlers receive an event and perform logic in response to the event being fired. For example, a UserRegistered event might be handled by a SendWelcomeEmail listener. Policies: This directory contains various policies of the application. Providers: This directory contains various service providers. Generating a Simple Application composer create-project --prefer-dist laravel/laravel blog This creates an app called “blog” in a directory called “blog”. It will be a 5.3 version. cd to the directory “blog” Run it using the provided local server: php artisan serve This starts the app on port 8000 It will contain a default home screen that is a set of links to Laravel education resources. We could go into /resources/views/welcome.blade.php and make changes. To adjust configuration, we create a .env file in the root of the application. This is organized as a set of key-value pairs. Setting up the Database Configuration Some of this is in app/config, and some is overrides located in the .env file There can be different .env files for local, staging, production, etc. Environment Configuration It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver locally than you do on your production server. To make this a cinch, Laravel utilizes the DotEnv PHP library by Vance Lucas. In a fresh Laravel installation, the root directory of your application will contain a .env.example file. If you install Laravel via Composer, this file will automatically be renamed to .env. Otherwise, you should rename the file manually. You may also create a .env.testing file. This file will override values from the .env file when running PHPUnit tests or executing Artisan commands with the --env=testing option. Retrieving Environment Configuration All of the variables listed in this file will be loaded into the $_ENV PHP super-global when your application receives a request. However, you may use the env helper to retrieve values from these variables in your Page 4 of 17 configuration files. In fact, if you review the Laravel configuration files, you will notice several of the options already using this helper: 'debug' => env('APP_DEBUG', false), The second value passed to the env function is the "default value". This value will be used if no environment variable exists for the given key. Your .env file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. If you are developing with a team, you may wish to continue including a .env.example file with your application. By putting place-holder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application. Creating Routes These define handlers. The handlers can be simple lambda expressions in the rout definitions, or references to controller methods (see below). Examples To be filled in Using Middleware Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Examples To be filled in Middleware groups You can define middleware groups in app\Http\Kernel.php. There's a new property named $middlewareGroups that's an array; each key is a name and each value is the corresponding middleware. Out of the box, it comes with web and api: protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; As you can see, the keys can reference either a class or a route-specific middleware shortcut like throttle or auth. Let's make an admin group: Page 5 of 17 protected $middlewareGroups = [ 'web' => [...], 'api' => [...], 'admin' => [ 'web', 'auth', ] ]; We've defined that the admin is a group that uses web (another group) and auth (a named route middleware). That's it! Creating Controllers Acts as a director for traffic between Views and Models. Open the command prompt or terminal based on the operating system you are using and type the following command to create controller using the Artisan CLI (Command Line Interface). php artisan make:controller <controller-name> --plain Replace the <controller-name> with the name of your controller. This will create a plain constructor as we are passing the argument — plain. If you don’t want to create a plain constructor, you can simply ignore the argument. The created constructor can be seen at app/Http/Controllers. You will see that some basic coding has already been done for you and you can add your custom coding. The created controller can be called from routes.php by the following syntax. Creating Views In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application. Create a view by creating a file under “resources/views”. There is no generator for a view file. Passing Data to Views While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file. Blade Templates Blade is a simple, yet powerful templating engine provided with Laravel. Blade is Laravel's lightweight template language and its syntax is very easy to learn. A blade template contains extension — blade.php and is stored at resources/views. Blade also supports all of PHP's major constructs to create loops and conditions — @for, @foreach, @while, @if, and @elseif, allowing you to avoid opening and closing the <?php tags everywhere in your templates. The main advantage of using Blade templates is that we can set up the master template and this master template can be extended by other individual pages. Creating Models for Persistent Entities The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. Page 6 of 17 Before getting started, be sure to configure a database connection in config/database.php. For more information on configuring your database, check out the documentation. Does the migration code get written automatically? Example To be filled in Operations using Models To be filled in User Management in the Default Application This is the most commonly-added facility on the base application. Want to get started fast? Just run php artisan make:auth and php artisan migrate in a fresh Laravel application. The tool will create the Login and Registration controllers and views (the data model for the user table and the password change history table was provided at application creation time). I think that the purpose of the password change history is so that a user cannot set a new password the same as an older password. Details of Controllers Login – quite simple because it contains: use AuthenticatesUsers to do most of the work. Registration – these creates user record – it creates and instance of the model and saves it. There are also the forgotpassword controller and the resetpassword controller Details of Views The login screen asks for username, password The registration screen asks for username, password (twice), etc. Database Migration and Seeding This facility is much like that provided in Ruby on Rails. Migration files, and Seeding Migration files define up and down schema changes. They express changes in the PHP-based “EloquentSQL”. In addition to running migrations, you can also seed content. To run all of your outstanding migrations, execute the migrate Artisan command: php artisan migrate The migrate:reset command will roll back all of your application's migrations: php artisan migrate:reset The migrate:refresh command will roll back all of your migrations and then execute the migratecommand. This command effectively re-creates your entire database: php artisan migrate:refresh Page 7 of 17 // Refresh the database and run all database seeds... php artisan migrate:refresh --seed Seeding files These create content in the tables. Troubleshooting If you have added a seeding file (perhaps manually), it doesn’t become part of the import sequence. In fact there is no explicit import facility in the PHP code. Instead there is a loader, which is driven by a file called “autoload”. Sometimes this will be out of date. Use “composer dump-autoload” to fix this situation. More About Models Now we will expand our knowledge of about model to include relationships, datatypes, defaults, etc. Defining Relationships Eloquent relationships are defined as functions on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as functions provides powerful method chaining and querying capabilities. For example, we may chain additional constraints on this posts relationship: $user->posts()->where('active', 1)->get(); But, before diving too deep into using relationships, let's learn how to define each type. One To Many A "one-to-many" relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Get the comments for the blog post. */ public function comments() { return $this->hasMany('App\Comment'); } } Remember, Eloquent will automatically determine the proper foreign key column on the Commentmodel. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id. Once the relationship has been defined, we can access the collection of comments by accessing the comments property. Remember, since Eloquent provides "dynamic properties", we can access relationship functions as if they were defined as properties on the model: $comments = App\Post::find(1)->comments; // } Page 8 of 17 foreach ($comments as $comment) { Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query: $comments = App\Post::find(1)->comments()->where('title', 'foo')->first(); Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method: return $this->hasMany('App\Comment', 'foreign_key'); 'foreign_key', 'local_key'); return $this->hasMany('App\Comment', Accessors and Mutators Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON. Filesystem/Cloud Storage Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system. Configuration The filesystem configuration file is located at config/filesystems.php. Within this file you may configure all of your "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver are included in the configuration file. So, simply modify the configuration to reflect your storage preferences and credentials. Of course, you may configure as many disks as you like, and may even have multiple disks that use the same driver. The Public Disk The public disk is intended for files that are going to be publicly accessible. By default, the publicdisk uses the local driver and stores these files in storage/app/public. To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public. This convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero downtime deployment systems like Envoyer. To create the symbolic link, you may use the storage:link Artisan command: php artisan storage:link Of course, once a file has been stored and the symbolic link has been created, you can create a URL to the files using the asset helper: echo asset('storage/file.txt'); Page 9 of 17 The Local Driver When using the local driver, all file operations are relative to the root directory defined in your configuration file. By default, this value is set to the storage/app directory. Therefore, the following method would store a file in storage/app/file.txt: Storage::disk('local')->put('file.txt', 'Contents'); Initialization Where is the initial content stored on Git? Using CSS Preprocessors Set up elixir. There is a package.json file in your Laravel project. Type “npm install”. Install gulp Type “gulp” or “gulp watch” The results of the CSS preprocessor will be added to “public” directory. Changes in Laravel 5.3 Laravel 5.3 continues the improvements made in Laravel 5.2 by adding a driver based notification system, robust realtime support via Laravel Echo, painless OAuth2 servers via Laravel Passport, full-text model searching via Laravel Scout, Webpack support in Laravel Elixir, "mailable" objects, explicit separation of web and api routes, Closure based console commands, convenient helpers for storing uploaded files, support for POPO and single-action controllers, improved default frontend scaffolding, and more. Laravel 5.3 ships with a more modern frontend structure. This primarily affects the make:authauthentication scaffolding. Instead of loading frontend assets from a CDN, dependencies are specified in the default package.json file. In addition, support for single file Vue components is now included out of the box. A sample Example.vue component is included in the resources/assets/js/components directory. In addition, the new resources/assets/js/app.js file bootstraps and configures your JavaScript libraries and, if applicable, Vue components. This structure provides more guidance on how to begin developing modern, robust JavaScript applications, without requiring your application to use any given JavaScript or CSS framework. For more information on getting started with modern Laravel frontend development, check out the new introductory frontend documentation. Along with Laravel 5.3, Laravel Elixir 6.0 has been released with baked-in support for the Webpack and Rollup JavaScript module bundlers. By default, the Laravel 5.3 gulpfile.js file now uses Webpack to compile your JavaScript. The full Laravel Elixir documentation contains more information on both of these bundlers: elixir(mix => { mix.sass('app.scss') .webpack('app.js'); }); When looping within a Blade template, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop. Page 10 of 17 In Laravel 5.2 you need specify middleware for routes like ['web'] or ['api'] but it doesn't required anymore. In 5.3 routes are stored in separated files and specify routes middleware not required. In 5.3, the app/Http/routes.php file has now moved to the root routes/ directory, and it's now split into two files: web.php and api.php. As you can probably guess, the routes in routes/web.php are wrapped with the web middleware group and the routes in routes/api.php are wrapped with the api middleware group. There are a few benefits of this. First, we get the suggestion and easy implementation of the distinction between our web routes and our API routes. Second, it's now an application-level convention to have multiple routes files, which will likely free more developers up to feel comfortable organizing their routes file this way. And third, this moves the routes directory out of app/, which both makes the routes directory more accessible to new users and makes app/ a fully PSR-4-autoloaded directory, which feels just a bit pure-r. Changes in Laravel 5.2 (July 2016) This release features multiple authentication driver support, implicit model binding, simplified Eloquent global scopes, opt-in authentication scaffolding, middleware groups, rate limiting middleware, array validation improvements, and more. Implicit model binding is a new feature that automatically binds a model to a route. Here is an example in code: Route::get('/api/posts/{post}', function(Post $post) { return $post; }); What this does is behind the scenes call Post::findOrFail($post) and injects it into the $post variable. For the seasoned Laravel developers, this is similar to the existing route model binding but now removes the step of having to bind it manually. Rate Limiting: A new rate limiter middleware is now included with the framework, allowing you to easily limit the number of requests that a given IP address can make to a route over a specified number of minutes. Middleware groups: When you are creating a site of any significant size in Laravel, your routes file will often get pretty large. One of the first things I do in a new site is group my routes by logically distinct sections like "admin", "auth", "public". Usually each of these groups get their own set of middleware—admin, for example, gets auth. Maybe the API group gets a different auth middleware, and it might get an API-specific rate limiter or something else. Laravel 5.2 has introduced something called middleware groups, which are essentially a shortcut to applying a larger group of middleware, using a single key. Example Projects Created LV01 The starter application, generated by Artisan for Laravel 5.3, with Authentication added in. Set up the database connection parameters in .env and .env.example. The database to be used must be created in MySQL, called “lv01”, then type “php artisan migrate” to set up the tables. LV02 A simple blogging application, with Posts, and comments. Using model files, and Eloquent SQL. Page 11 of 17 The database to be used must be created in MySQL, called “lv02”, then type “php artisan migrate” to set up the tables. LV03 Example of crud using Ajax. Questions/Open Issues Is there a way to define modules (distinct sets of M/V/C)? What about generating a menu? What do I need to configure to use AJAX? What do I need to configure to use Vue? Appendix A: Tutorial This is from http://www.tutorials.kode-blog.com/laravel-5-tutorial Introduction Laravel was developed out of the need to address most of the challenges in CodeIgniter MVC. Laravel is built on the shoulders of giants. It uses components from other time tested frameworks like Symfony. If populating is anything to go by, Laravel MVC has the Lion’s share in the PHP MVC frameworks market share. According to a survey done by SitePoint, Laravel MVC framework is the most used framework in both personal projects and at work. Installation and Configuration We will cover the following topics. Pre-requisites for installing Laravel How to install Laravel using composer How to check if Laravel installed correctly Laravel directory structure Configuring a new Laravel project Application configuration The application configuration information is located in /config/app.php. In this section, we are going to; Set the debugging mode – the debugging mode is used to determine how much information should be displayed when an error occurs. Set the time zone – this setting is used for PHP date and date-time functions. Application key – this value is used for encryption purposes. Authentication configuration The authentication configuration file is located in /config/auth.php. We will leave the default values as they are. If you want you can change them to meet your requirements. Database configuration The database configuration file is located in /config/database.php. By default, MySQL will be used as the database engine. You can set it to a different database management system if you want but for this tutorial, we will leave the default value. Page 12 of 17 We will update the following keys: database username password Hello World At this point write the first controller, and the first routes. SEO-Friendly URLs In the previous tutorial Laravel Hello World, we looked at routing and controllers. In this tutorial, we will build on that knowledge and do some actual work on our tutorial project. We will cover the following topics Factors that affect SEO o Website speed o Role of Social Media in SEO o Responsive designs and mobile friendly o Keywords o Website URLs How to implement SEO friendly URLs in Laravel At this point, we create a new controller called Front. We also replace all routes. Summary: The discussion was incomplete, but the intent was on target: Developing web sites that simplify search engine optimization will make SEO experts love your web applications and this will have the sinful effect of making you a hell lot of money. Always remember the factors that affect SEO and incorporate them into your public web applications. Blade Template Blade is a powerful easy to use template that comes with Laravel. Blade templates can be mixed with plain PHP code and it will still work. We are using the HTML5 template E-Shopper from ShapeBootstrap We will cover the following topics Template inheritance Master layout Extending the master layout Displaying variables Blade conditional statements Blade Loops Executing PHP functions in blade This lesson first introduces you to the features of Blade, such as sections, layouts, overrides, etc. Then we download and install about 9 different templates, then change the Front controller, then install resources. These files are using Bootstrap 3.0.3, while the generated Laravel files are using Bootstrap 3.3.7. We should be able to take out page and welcome templates, and their routes. At this point, we have about 9 different pages (and sidebar) of a shopping site, but no dynamic content. All of the images are static, too. But the site looks very good! Page 13 of 17 Migrations Laravel migrations provide mechanisms for creating and modifying database tables. Migrations are database agnostic. This means you do not have to worry about the specific SQL syntax for the database engine that you are creating tables for. Migrations also allow you to roll back the most recent changes that you made to a database. We will cover the following topics Requirements for running migrations Artisan migration command Migration structure How to create a table using a migration Laravel migration rollback Laravel migration how-tos Database seeding Larashop database dictionary Migrations for Larashop database dictionary This is organized in a way similar to above: first we learn the concepts by creating several migration files for tables that are really just test cases, then we move on to the actual tables for larashop. I had problem which required using 127.0.0.1 instead of localhost in the db configuration. The Faker system for generating data was quite useful. We first need to install Doctrine Database Abstract Layer DDBAL in Laravel before we can change columns. DDBAL is used for Laravel migration alter table tasks. The discussion about setting up relational links was important. The notes about allowing dates to be null were needed. Perhaps this is a change from 5.0 to 5.3. At the end of this tutorial, we have a product/category/brand data model in place and seeded. Eloquent ORM We will cover the following topics in this tutorial Eloquent ORM Models o naming conventions o table name and primary keys o timestamps Laravel 5: Run raw SQL statement Eloquent ORM INSERT Eloquent ORM READ Eloquent ORM UPDATE Eloquent ORM DELETE Eloquent ORM models for Larashop tutorial project Larashop: Using models in controllers Larashop: Displaying data from models in views In this section, we created a few models, discussed the important fields and control functions in them. There is a BaseModel that all inherit from. Then simple examples using simple routes. Finally, we bring in the latest code of FrontController, and update the views. In the resulting code, the products, categories, and brands are driven by database fetches. Page 14 of 17 Shopping Cart In this tutorial, we are going to implement the shopping cart functionality. We will use a package developed by Crinsane. We will cover the following topics in this tutorial Installing Laravel Shopping Cart via composer Configuring Laravel 5 to work with Shopping Cart Adding items to the shopping cart Retrieving items from the shopping cart Updating items in the shopping cart Removing items from the shopping cart Clear all items from shopping cart This part of the tutorial brings in much more code (a third-party package), and shows how to use composer to perform this. After that, we included the Cart functionality from the package in our Front controller, and implemented the “cart” request handler to use the Cart object. I completed the exercises of implementing the “delete from cart”, and “clear cart functions” as well. The author of the tutorial indicated that this was a stopping point, but (perhaps later) more tutorial steps were added. We will continue with those. Authentication One of the advantages of Laravel is that it comes with authentication built in into the framework. It is very easy to use. In this tutorial, we will implement authentication for the Larashop checkout page. We want to ensure that only logged in users can check out. We will cover the following topics in this tutorial: Laravel 5 authentication configurations Laravel 5 basic authentication How to change the default login URL Laravel 5 custom authentication It appears that the login and register scaffolding was added when we integrated the views from his download. So all we had to do was wire up the login/logout/register methods, and adjust the header area of the main layout to indicate if the user was logged in. Interesting that I had to import Redirect in order to use it – the tutorial didn’t mention that. For that matter, the code also imports Request, perhaps these imports were no longer assumed in Laravel 5.3. REST Almost all successful Internet-based companies have APIs. API is an acronym for Application Programming Interface. APIs allows different systems to communicate with one another. Let’s say you have developed an android application for our online store. The API can be used to retrieve data from the online store and display it in the mobile application. The API can also be used to process orders from remote clients such as mobile applications, other websites etc. We will cover the following topics: What is a RESTful API? REST API Best Practices Page 15 of 17 Larashop API 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Best Practice # 1: Use HTTP VERBS to determine action to be taken Best Practice # 2: API Versioning Best Practice # 3: Use plurals to describe resources Best Practice # 4: Use query strings to build relations Best Practice # 5: Partial responses Best Practice # 6: Response Codes and Error Handling Best Practice # 7: Limit the number of request in a given time period from the same IP Address Best Practice # 8: Use OAuth latest version for authentication Best Practice # 9: use JSON as the default Best Practice # 10: Cache GET results for less frequently changing data For now, we will only provide access to the products and categories. Our API will implement basic authentication only. The paths are /api/v1/products and /api/v1/categories Use a registered email address and password from the previous tutorial on Authentication. The tutorial had us putting routes into Routes.php. As of Laravel 5.3 should it go into web.php or api.php? they should go into api.php, and you don’t need to add “/api” to the path for each. Blogging You can use a blog to publish valuable, relevant, and consistent content. Blogs can also be used to publish video, audio, pictures, or written content etc. Features of a success blog Post Categories Tags Related Posts Comments User experience Newsletter Technical SEO factors Post Title Meta Description Role of Social Media Larashop Blog Database Migrations Tutorial Project Larashop Blog Implementation We are adding the following tables: BlogCategories - one of four specific values for the categories BlogTags – just an id and a string BlogPostTags – a many-to-many resolver between Post and BlogTags Plus we have changed Post to have a category id. Our blog still needs a lot of work before we complete it. We haven’t yet implemented the comments section and the social media aspect of it. The next tutorial will focus on the custom comments section and integrating social media. Page 16 of 17 It seems like we also have not implemented adding a new post. There were also more typos and errors in this part of the tutorial than what we have seen before. Ajax In the previous tutorial, we implemented the blog for Larashop. In this tutorial, we will cover the basics of Ajax and create a simple CRUD Laravel Ajax example. As a tutorial exercise, you will be required to use the knowledge you will gain to implement the commenting system for Larashop. The tutorial will first cover the Ajax theory, discusses the advantages and disadvantages then show you how to do the implementation. If you are already familiar with the theory then you can skip it and go to the implementation. We will cover the following topics in this tutorial. What is Ajax Why use Ajax? When to Use Ajax jQuery Ajax API Laravel Ajax CRUD Example Larashop Ajax Commenting System This example was good on the concepts, but not very complete in implementation. It was a CRUD example using Ajax. The biggest complication was that it used simple jQuery code on the client side, so we were programming at a very low level. However, the example was then used to build my LV03 example. Page 17 of 17