PHP (Laravel)
Hope this article saves you from all those irritating Laravel jargons when developing for the first time.
Server Setup
Install Laravel
Environmental Variables
There is a .env
(or .env.example
if not using Composer to install Laravel) file at the project root. Configuration files like config/app.php
would look for configuration value in this .env
file.
To make your modifications work, use php artisan config:cache
to recache it.
Developing for Laravel
Like many other web frameworks, Laravel renders a page or API with four main modules: The first one (jargon: route) matches the url to a handler module. The handler module (jargon: controller) is where you write the core business logic for the page or API. It could call a data module (jargon: model) for data from databases or other storages. Finally it sends the processed data to the last module (jargon: view) which formats and generates a response. Of course there are many other modules, classes and libraries supporting these four. But we'll focus on these first.
Develop Web Pages
Show your page: First we define the url and the corresponding handler class/method at
routes/web.php
:Now for our
TestController
:Finally we write our new view module
test
:And just put in any valid HTML code.
You can run the Laravel built-in server locally using command
php artisan serve
. If you are developing on your local machine with a browser, you can go tohttp://127.0.0.1:8000/test
and see your page. Otherwise using commandcurl http://127.0.0.1:8000/test
to see your server output.Insert your data: First we create our database table and a corresponding data module (model) to manipulate the table. Then we call this model from controller to insert data. The model of Laravel provides us with a lot of conveient APIs to manipulate data tables without writing SQL.
To post data to a url, simply add this to
routes/web.php
:
Create our controller:
Create our table and model. Laravel provide scripts (jargon:migration) to create tables for us.
Now if we post something to our url, you can see the result.
Retrieve your data: Similarly, we edit our route and controller file:
Update your data: The only difference from create and retrieve process is the model API we use in our controller:
Front end: It's going to take a long time introducing the modern front end technology stack. If not interested, you can use old-fashion HTML/CSS/JS in Laravel like this:
If you do have the patience to learn, Laravel has the most popular front end frameworks (Bootstrap, Vue, React) and module bundler (Webpack) builtin for us. So you can easily reap the benefit:
Every time you modifies JS or SASS, run
npm run dev
to generate final JS and SASS assets.Pagination:
Handling user: Usually if you are letting user posting content on your site, you need to implement register, login, verification, password reset, session and logout the whole package. How to implement all of these is beyond the scope of this article. Luckily Laravel has these all built-in for us. Using the command below will generate all the code, including route, view, controller and model, for us:
If you are curious about how they are implemented, you can show all the routes in your app now using command
php artisan route:list
. (They hid them behind aAuth::routes();
function call so you won't see them atroutes/web.php
). Their controller code are at https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Auth/AuthenticatesUsers.phpYou can control where your app jumps to after login at
app/Http/Providers/RouteServiceProvider.php
public const HOME = '/home';
.
Develop APIs
Request validation: create a request class and put our validation code there:
Finally, put it to work by replacing the request class in your controller
app/Http/Controllers/NoteController.php
:Force JSON response: Laravel has prewritten some API code for us, but did not enforce a JSON reponse. Since nowadays it would be strange to most clients that an API returns a HTML page instead of a JSON object, for most of us we'd better enforce JSON reponses on API calls ourselves.
Obviously it would be a bad idea to force Laravel to return JSON on every kind of request. Surely We can return JSON from our controller code. But when there is an exception, including validation failure and authentication failure, the default way of Laravel handling it is still returning HTML.
That's why the healthy way would be distinguishing requests from API calls and webpage calls, and only enforcing JSON response on API calls. This method below is borrowed from @DarkGhostHunter at medium and others:
Define a function (jargon: middleware) that sets all incoming HTTP request header 'Accept' to 'application/json'. We later use this to distinguish API calls.
Register this middleware to Laravel by modifying
app/Http/Kernel.php
file:
Put it to work. Add
request_json
middleware toroutes/api.php
file:
Modify all the exception handling code in one place
app/Exceptions/Handler.php
:
Log
Laravel supports eight logging levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info and debug:
Query your database
Create your tables in database
Laravel provides us with a fancy command to generate a PHP script that create or modify table schemas for you. The idea behind this is to keep track of all the database modifications in a series of PHP files. So it is kind of like version control of your database schemas:
This script grammar is listed here: https://laravel.com/docs/master/migrations. Remember it is best to implement the
down
method in case you need to rollback your modification in the future.
Last updated
Was this helpful?