ICTShore.com

We re-branded, ictshore.com is now accelerates.it!

PHP Laravel Tutorial: Setting up your project

A complete Laravel tutorial to get you started.

Share This Post

In the past, we talked about the importance of having a great project structure in PHP. However, it is not always easy to create such a structure on your own. An alternative to that is using a framework to ensure your project will last and be scalable. Laravel is a valid option for that since it enforces a great structure and it is easy to learn. Furthermore, it adds some very nice features that can help you deploy great applications, and integrate them in your DevOps approach. In this PHP Laravel tutorial, we will see how to create a project with Laravel, and how to use Laravel features to quickly build our web app.

Part 1: Getting your project up and running

A Project based on Laravel

The first thing we need to do, as part of this PHP Laravel Tutorial, is to get a project ready with Laravel. Fortunately, this is very easy if you have composer installed. If not, simply download it from here, and don’t forget to check our tutorial about composer.

Once you have composer, ensure you have it and PHP in your PATH Environment variable. This way, you can call from anywhere in the command prompt the two commands composer and php. Then, you can use it to set up your project. The first thing you need to do is create a new folder to host all files of our project. In this example, we are going to use D:\MyLaravel. However, you don’t need to create this folder manually. Navigate to the root folder where you want your project to appear, then use the following command.

composer create-project laravel/laravel MyLaravel

This will create a new Laravel project named MyLaravel, creating that folder as a first thing. Of course, use the name of your project instead of MyLaravel. Once the folder is created, composer will automatically load the Laravel files of the last stable release and set up your project. This can take a few minutes, depending on your Internet connection.

Serving the project

The best part of our PHP Laravel Tutorial is that we can see the results of our changes immediately, even without a web server installed. To verify that everything is working correctly after the installation, navigate inside your project folder. Here, run the following command.

php artisan serve

This will launch a mini webserver to make the application available locally. In other words, you can browse and see the pages you are creating. Be aware that this webserver is a test web server. You should never use it in production, as it is not designed to scale. It cannot handle more than a couple of requests, and with limited scalability. Once you launch that command, you should see something like the following output.

D:\MyLaravel>php artisan serve
Laravel development server started:

Now, if you browse at that URL, you will get the default Laravel project home, something like the following.

PHP Laravel Tutorial: this is the view you will get once you installed Laravel succesfully.
The default view of a new Laravel project.

In the terminal, you can see that requests are logged for easier troubleshooting. Once you are done, you can shut the server down with Ctrl+C in the prompt. As a tip, you can customize the port to a port different from 80 or 8000 with the --port option, like --port=100.

Artisan is a powerful command-line utility that helps you working with your Laravel project. It does much more than just running a development server. We will see that later on.

Part 2: Inside the Laravel Project

Model, View, Controller (MVC)

MVC is a popular architectural approach to web applications. In fact, most modern web applications are designed with this approach in mind. As a result, you will find many frameworks of different languages implementing the same concepts. Laravel is one of them. Before we dive into the details of our project, we should briefly present this approach.

With MVC, we think about applications as systems that present and allow us to modify information. We represent each piece of information with a Model. For example, a website that allows you to make Hotel reservations will allow you to see, create, and modify reservations. The reservation is the Model. Of course, a single web application will work with several models at the same time. To continue with the Hotel example, Hotels and Rooms can be other models inside the same applications. Not to mention users themselves.

We serve applications over the web, typically with HTTPS. This means we need to allow the user to view and modify our models through that protocol. That’s where views and controllers come in. A controller is a processor, something that works on the models. It may just search some of them and show the results, or even modify them. Instead, a view is the piece of the application that deals with interacting with the user. It takes care of presenting the data in a way that is human-readable, and give the user the buttons and forms to trigger actions.

MVC separates the logic (controller plus model) from the user interface (view). This makes the design easy to maintain and scale.

.env

The .env file contains all the information Laravel needs to run your application on this machine. If you move your application from a server to another, you can have a different .env file for each server. That file, in fact, describes the environment, and you can find it at the root of your project. You may want to open it and tune it. Specifically, if you plan to use a database, you need to modify the following part.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Laravel supports several databases, like MySQL or PostgreSQL. It can also support SQLite to get you started quickly. Edit the file to point to a valid database. In case you don’t have one, I suggest installing MySQL (which on Windows comes automatically with XAMPP).

Create a Model

As a first part of our PHP Laravel Tutorial, we need to create a model. Typically, each model is just a code representation of a table in the database. The creation of the table in the database is handled by Laravel itself, but outside the model. In other words, you don’t need to write SQL queries to create a table for your model. Still, creating just the model itself is not enough. The model is a representation in the code, while you need a migration to act on the database.

Thus, to create a new model named Reservation, we can use the following command.

php artisan make:model Reservation --migration

This will create a new Reservation.php inside your app folder, and also create a new file in the database/migrations folder. The first thing we need to do is edit the migration file, here is where we will define the fields the table must-have. Here is an example of the migration. Note the lines we added.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateReservationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('reservations', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            // We add the following lines:
            $table->string('code');
            $table->dateTime('start_date');
            $table->dateTime('end_date');
            $table->string('notes')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('reservations');
    }
}

The migration is just a set of instructions to manipulate your database. You can have many migrations, and they will run in sequence when you launch them. Each migration has a up() function, used to actually apply the changes, and a down() function, that should contain the code to roll-back. To apply our migrations to the database, we run the following command.

php artisan migrate

This will run migrations from the first migration that never ran. However, you may want to run the migration from the beginning, after clearing the database. If that’s what you want, run php artisan migrate:fresh.

Using a model

Now that we created the migration and that we have the table in the database, we can access its records using exclusively the model. To create a new record, we simply instantiate it. Then, we can access its fields like attributes of the object, like the following.

<?php

$res = new Reservation();
$res->code = 'XCW-45D-CRZ';
$res->start_date = '2019-12-01';
$res->end_date = '2019-12-07';
$res->save();

?>

This will automatically populate the id (because we made it autoincrement on the migration) and leave the notes to null. As you can tell, the save() function stores the data in the database.

To load a model, you can use the class statically and use the where() clause, like the following.

<?php

// With get() you get the entire collection
$res = Reservation::get();
foreach ($res as $r) {
    echo $r->code;
}

// With first() you get only the first item of the collection directly
$res = Reservation::where('id', '1')->first();
echo $res->code;

?>

If you omit the second parameters, it will assume a simple equal comparison. You can load a model, change some of its fields, and then save it back to the database.

Controllers

Create a controller with the make:controller option, and provide a name for your controller. It will land in app\Http\Controllers.

php artisan make:controller ReservationController

For simple controllers that work only on a model, it is a best practice to name then with the name of the model, followed by Controller. Here you can create functions that process user requests and modify models.

ReservationController extends Controller
{
    /**
     * Modify a reservation
     *
     * @param  Request  $request
     * @return Response
     */
    public function edit(Request $request)
    {
        $r = Reservation::where('id', $request->id);
        if ($r)
        {
            $r->code = $request->code;
            $r->save();
        }
    }
}

You can name your functions the way you want. In this example, we have an edit function that must take a Request object has parameter. It will look for an existing request, and if it exists it will update the code with the one provided in the request. The attributes of the request are nothing more than the data provided in a POST form.

Now that we have our controller, we need to map it to a URL. We can do that with routes.

Routes

Routes simply map URLs to controllers or views. They are inside the routes folder, and specifically URLs for the users are in the web.php file. You can customize routes and create your own files here, but we won’t do that for now. Here is our example web.php file.

Route::get('/reservation/edit', 'ResourceController@edit');

The syntax is very simple. First, you need to use the Route class. Then, a static method corresponding to the HTTP method you want to listen, like get, post, put, or delete. The first parameter is the relative URL, and the second can be an anonymous function (like in the first case). It can also be the name of a public method on a controller, like in the second case. Now, we can call our controller with a POST request to /reservation/change-code.

In the first example, we simply return the view named welcome.

Views

Views are basically enhanced HTML code. You can find them inside the resources\views folder, and each must have the extension .blade.php. Take a look at the welcome view. We can edit to have a form to call our controller, and it can look something like this.

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

Our first view

<form action="/reservation/change-code" method="POST">
  <label>Reservation ID</label><input name="id" type="text">
  <label>New code</label><input name="code" type="text">
  <button type="submit">Update</button>
</form>

However, views are not simple HTML. They can have some basic logic in it. For example, you may want to show the Login button only if the user is not authenticated, and show the username otherwise. That’s completely possible with views. When calling a view, you can provide some parameters by providing an additional argument array, like below.

return view('welcome', ['message' => 'A sample message']);

Then, you can use those parameters inside the view by putting their name in double curly brackets. In this example, we would need to use {{ $message }}. You can also use if and else statements, like the example below from the Official documentation.

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Wrapping it up

With this PHP Laravel tutorial, you should be up and running with Laravel. We didn’t dive into all the great parts of this framework, like configuration or middlewares, but that’s enough to get us started. You should try Laravel a little bit, and see if it works for your project and style of programming. What do you think of it? Let me know in the comments!

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio

2019-07-04T16:30:41+00:00

Unspecified

Dev

Unspecified