6 min read

Laravel From Zero to Hero 00: An Introduction to Laravel

Contents

What is Laravel?

Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things. – laravel.com

Laravel is a web framework built with PHP and gives you the tools you need to create a website.

Why Choose Laravel?

Laravel makes PHP development an absolute joy. PHP also gives you so many options since there’s plenty of other frameworks around such as Symfony, Slim, Cake and many more. Laravel has clear, concise documentation and answers most of your worries.

It covers a broad range of issues which you might come across when developing in any language, but they don’t all come bundled together. Laravel is very well pieced together, and Taylor has managed to keep the core compact while allowing you to expand on the framework through Composer packages.

Laravel’s packages are very easy to install and have plenty of documentation to cover them as well. If you can’t find your answer then Laravel has an absolutely fantastic community who are always helpful and love to help newcomers.

Routing

Routing is one of Laravel’s core concepts and allows you to set out your app’s structure. Firstly, you have web.php where you can place all your web requests, this is where you’ll find frontend and form request/responses. Secondly, their api.php which is where you’ll place any API requests. Representational state transfer aka REST is the most popular architectural choice for creating APIs which we’ll learn more about in the future.

For the first section of our course, we’ll be using web requests/responses and later move over to JSON API requests/response where it will all become clear.

<?phpRoute::get('/', function () {    return 'Hello World';});
A simple closure based route in web.php

From the above code, you can see a web route in its simplest form. Firstly, we’re creating a get request so when someone visits example.com/ they’re asking to get the information for the page, they’ll then see the text “Hello World” which is being returned from our closure function.

There any many other route methods which help us deal with web and API requests. These include the following…

Route::get($uri, $callback);Route::post($uri, $callback);Route::put($uri, $callback);Route::patch($uri, $callback);Route::delete($uri, $callback);Route::options($uri, $callback);
List of all route form method

A lot of our requests will be more complex and we’ll want to separate the logic from our routes file. This can be done through controllers, if we wanted to move the above code from closure to a controller we will need to create our first controller.

Head over to app/Http/Controllers and create a file called HelloWorldController.php then add the following code.

<?phpnamespace App\Http\Controllers;use App\Http\Controllers\Controller;class HelloWorldController extends Controller{    public function index()    {        return 'Hello World';    }}

And we’ll edit our web.php as follows

<?phpRoute::get('/', 'HelloWorldController@index');

As you can see, we’ve removed our closure and swapped it out for the HelloWorldController and pointed it to the index method. The method then returns the same ‘Hello World’ as before, but now the logic has been separated. As your code becomes more complex, it makes sense to separate logic from one another.

Blade Templating

This brings us over to Blade templating which is a template language for our frontend code. Blade templates are just as expressive as the rest of the Laravel framework and make frontend development a joy.

<p>Hello, {{ $name }}</p>
Blade templating in it’s simplest form

For our next example, we’ll create a new dynamic route. It’s dynamic because it will accept user input and output it as HTML.

Let’s start by updating our current route to accept user

<?phpRoute::get('welcome/{name}', 'HelloWorldController@index');
{name} will take text from the URL bar

In our index method of HelloWorldController.php let’s update to accept our name input and return the output.

public function index($name){    return 'Hello ' . $name;}

Now when you head to example.com/welcome/Michael you’ll see the text “Hello Michael”, but we still haven’t use Blade templating.

Let’s update our index method to return a blade template

public function index($name){    return view('welcome', ['name' => $name]);}

Head over to resources/views and open welcome.blade.php. You’ll see there’s already code in this file since it’s Laravel’s default. Go ahead and delete everything inside and add the code from below.

<p>Hello {{ name }}</p>

Now when you visit example.com/welcome/Michael you’ll see a similar result to before, but now we can add as much HTML code as we like and we can also add CSS and JavaScript to the mix as well. You can also create templates for specific pages much more.

Eloquent and the Query Builder

If you need to interact with a database, you can do this with Eloquent.

$user = new User();$user->username = 'awesome_user';$user->password = 'shh, this is a secret';$user->save();
Creating a new user and saving details to the database

Or maybe you like to create your own database queries.

DB::insert('INSERT INTO users (username, password) VALUES ("awesome_user", "shh, this is a secret")');// or using the query builderDB::table('users')->insert([    'username' => 'awesome_user',    'password' => 'shh, this is a secret']);
Create raw queries or the query builder

As with any raw queries, you must always be careful with user input and the potential for SQL injection vulnerabilities.

$username = $request->input('username');$password = $request->input('password');// Not okay - NEVER DO THIS!!!DB::insert("INSERT INTO users (username, password) VALUES ($username, $password)");// Escaping user input - DO THIS!!!DB::insert('INSERT INTO users (username, password) VALUES ?, ?', [$username, $password]);
Unsafe SQL queries compared to safe SQL queries

What are Tests?

Tests are apart of every programming language. PHPUnit is the most popular package for testing in PHP, but there is also Codeception, PEST, Dusk, Behat and many more.

There are also different types of tests, the most popular are:

  • Unit testing tests a specific chunk of code.
  • Behaviour-driven describes what a user should expect in a much more readable and business-friendly way.
  • Frontend testing where you test how your site should behave in a web browser.

Laravel developers mostly use PHPUnit for backend unit testing and Dusk for frontend tests. We will be covering both and it will be up to you whether you want to carry these tests out within your projects, but it is highly recommended you do.

What is TDD?

TDD stands for Test Driven Development and it’s the practice of creating tests BEFORE you create anything else. The practice will look a little something like this…

Create a test for a specific task
Run the test
Test fails
The failed test will say why it failed
Write code for that error
Run test which may pass or fail
If the test fails, write more logic

When the test eventually passes, you can move onto another test and repeat the process. It may seem pointless and it may seem tedious, but once you get the hang of it, you’ll see the benefits.

Why should I test my code?

Say your senior developer comes up to you and requests a change in logic. Your code has no tests and there are no specifications to how it should currently work. You try your hardest to understand the logic and you think you know what’s going on.

You try to implement the change and introduce new bugs into the code. You’re unaware of said bugs because there are currently no tests implemented and as far as you can tell, everything works as expected.

You create a Pull request and your senior tests your code. They find bugs which you weren’t aware of and ask you to fix them. You take a look, fix the bugs they found and create a new PR. He reviews it again and finds the bugs are fixed, but unfortunately, they find another bug. You fix that bug and cross your fingers everything works as expected.

With this new PR, your senior reviews the code and approves your work. It’s taken a couple of back and forths which could have been easily avoided if you had tests running.

Now we have the exact same situation, but with a test suite. After receiving the request, you look at the tests and run them to ensure everything is working in its current state (which it should be).

All tests come back green and you begin to update the tests for your new logic. Once you update the tests, you run them and make sure it should fail since nothing has been implemented yet. It comes back red and tells you why it failed. You write some code and the test fails again but gives you a reason.

You follow these steps until your logic is complete and all tests pass. You push your code and create a PR. An automated test suite picks up on your PR and runs its automated tests. Everything comes back green again and your senior gives it one last review to ensure it’s up to coding standards.

Everything looks good and your senior is happy to merge and eventually pushes it to production.

The second scenario had a lot less friction between you and the senior and they are now a lot happier with your work.

Closing thoughts

I hope this gave you more insight into the Laravel framework and the TDD methodology we will be using from now on in this course. This episode is open to the public, but if you want to see future posts for this course, you will need to sign up using the form below.

If you have any questions, then you can use the comments section below or hit me up on Twitter or Facebook.