An Introduction to Laravel – Basic Tutorial

If you’re reading this article, that means you’re interested to learn Laravel. We will learn how to build applications with Laravel. But, let’s start from the beginning, shall we?

This will be the basics you need to know about Laravel before you can build your application.

The purpose of this tutorial is to teach you the basic concepts that you need to understand to build an application with Laravel.

Note : This tutorial is based on Laravel 10, but it also works for previous versions and will be updated if new version comes up.

What is Laravel?

First of all, we need to know what Laravel is.

Laravel is a PHP framework (a supporting structure which can be used to build an application). It’s as simple as that. Laravel comes with expressive and elegant syntax. You can think of it as the foundation to build your application quickly and elegantly.

Imagine you’re building an ecommerce web application with PHP. There are a ton of things you have to set up, the database connection, the SQL syntax and everything else. Now, with Laravel, a lot of that is already set up for you. You already have the building blocks, you just have to build on it.

There are a lot of other frameworks obviously, but Laravel excels in its simplicity and usefulness. It has a lot of features that can be used. Authentication, for example, is a complex process and it can be done easily with Laravel. How easy and quick it is to use to build complex applications is the reason why many people use it.

Laravel was created by Taylor Otwell in June 2011. In fact, it was created as an excellent substitute for another PHP framework, which is CodeIgniter. As of May 2023, Laravel has come a long way and is on version 10. It now has even more features and is even more useful than ever.

Prerequisites

Before we start learning the basic concepts of Laravel, it is best if you’ve understood these concepts beforehand. You need to have these installed in your desktop as they are essential for running Laravel.

  • PHP – a server-side scripting language, comes preinstalled with XAMPP
  • HTML – a standard markup language to build web pages, comes preinstalled with your browser
  • MySQL – database, comes preinstalled with XAMPP
  • Web server (XAMPP, etc) – a combination of software and hardware that serves a resource (web page) when requested. For development, we’ll use XAMPP as our local web server.
  • Composer – dependency manager in PHP. It is needed to install Laravel.

Installation / Your First App

To create a Laravel project,

  1. Open terminal and cd into the directory where you want to place your project
  2. Run this command, composer create-project laravel/laravel projectOrFolderName. This command will automatically install the latest version of Laravel for you (note: if your PHP version supported it)
  3. Project created. To run the project, cd into the folder
  4. Run this command, php artisan serve and go to the URL shown (usually it’s http://127.0.0.1:8000)

Your project is up and running. To modify your project, open that project folder in your favorite text editor.

Default Laravel View
Default Laravel View

Also, to stop the server running, just press Ctrl + C.

The Basic Concepts

Laravel has a lot of capabilities. These concepts will give you the minimum understanding to create a functional Laravel application, at least a CRUD (Create, Read, Update, Delete) application.

.env

First things first, is the .env file. It is a setting for your project that contains environment variables for your application. It includes information like your project name, database name, your email service host if you use one.

.env files are supposed to be personal and each developer should have different .env file for the same project so they can test the project locally. For example, there are two developers working on the same project. One developer can name his database ‘table’ while the other name it ‘data’. If you use GitHub, .env file is not pushed to the repository and you should make one yourself by copying .env.example.

When you first create a Laravel project, .env file is the one that you usually edit first, since you want to set the database you use. Just set DB_DATABASE to your database name. Don’t forget to set DB_USERNAME and DB_PASSWORD accordingly. If you haven’t changed them, root and empty string are usually the default settings.

Routes

Just as its name sounds, the routes folder manages the routing of your application. It’ll determine what you will see if you open ‘yourproject.com/home’ for example.

It is usually one of the first things we do when we make our project. To manage the routing, go to your routes folder and open web.php. Inside it you should see this code (I deleted the comment to keep it from getting too crowded).

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

That code means when you open that url, a function will be run and that function shows a default welcome page. To understand more, try to modify it. And also, don’t forget to run php artisan serve to check your page.

Route::get('/', function () {
    return 'Hello';
});

Route::get('/newPage', function () {
    return '<h1>It is another page, but with a h1 tag</h1>';
});

Now, your main URL will show a hello text. You can also return HTML tags like in the new route we created.

Notice that we use get after Route::, that means we’re using GET method for that URL. As we go further on, we’ll use other methods such as POST, PUT and DELETE.

Views

The views folder is where you place your User Interface. Usually you use index.html or index.php. But, Laravel uses a templating engine called blade. So, we use index.blade.php instead.

Modify your route/web.php, change the function to return view('index'). It’ll automatically look for index.blade.php in resources/views folder. That’s what we’ll do next.

Route::get('/', function () {
    return view('index');
});

Open resources/views folder and create index.blade.php. You can put some standard HTML code in it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Home</title>
</head>
<body>
    <h1>Hello</h1>
</body>
</html>

Now, I’m going to show you where blade really stands out.

But first, we have to explore our routing a bit. You can pass data through objects in the routing like this,

Route::get('/', function () {
    return view('index', ['name' => 'John Doe']);
});

Back to our index.blade.php, modify our h1 tag to show the name. We use double curly brackets {{ }} to escape HTML entities and echo or print PHP expressions.

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

And now, your page should display ‘Hello, John Doe’.

Database (Migrations)

When we’re making a web application, most of the time, database is a must. Laravel made making and maintaining database so much easier with migrations. Migrations are sets of commands to make changes to your database. This is especially useful when you’re working with other developers as you can just share the migration and they run the migrations. Their database will be updated to be similar to your without them manually adding or deleting tables.

Remember that we set our DB_DATABASE in .env? We have to create our database manually. In my case, I use phpMyAdmin to make it. For example, my database is named laravel-basic. Don’t forget to turn on your web server (XAMPP, for example) when you want to access your database.

Open database/migrations folder, that’s where the migration commands are stored. You’ll see there are a few migrations already there. Those are the default migrations from Laravel and are very useful. But, to keep this tutorial simple, we’ll ignore them and make a new migration.

To make a new migration, run this command in your terminal. Change ‘posts’ to your desired table name. For this tutorial, I’ll use posts as example. The command name format (create_pluralName_table) is a convention from Laravel and it’ll automatically format your migration to create a new table.

php artisan make:migration create_posts_table

The migration is created. Modify the up() function just like the code below. Then, run ‘php artisan migrate’ in your terminal and the table will be created.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

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

Up() function is a command to make your table according to the specifications you wrote. On the other hand, down() function reverse the up() command. In this case, it’ll delete the table. down() command will be run when you use ‘php artisan migrate:rollback’ command. It is used when you feel the migration needs to be changed, so you roll it back, correct the migration and run the migration again.

Models

The database is created. Now, we need a way to interact with them. Lucky for us, Laravel comes with Eloquent ORM (Object-Relational Mapper). It helps us manage our data by representing them as objects through Models.

You can think of Models as a singular representation of a table. For example, we have a table named ‘posts’, so our Model for that table is ‘Post’.

Let’s create our Model. Run this command.

php artisan make:model Post

The created model will be stored in app/Models as Model.php.

In the model, you can determine various informations, like the primary key, the relationships, the columns that can be edited and many more. For now, let’s add $fillable so we can add data to our database.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'description'];
}

The model will immediately know that your table name is the model’s name in plural form, which is posts. If you want the specify the name, add protected $table ='table-name';

To try out the model, we’ll show a data from that model.

Go to web.php, call the model. Place this code on top, just below use Illuminate\Support\Facades\Route;

use App\Models\Post;

This code means that we’re using the Post model. How can we know the path (App\Models)? Go back to Post.php and you’ll see there’s a namespace which is App\Models. That’s your path, just add your model name to it.

Now, modify the route to print all the data in our database. It won’t show much since it’s still empty. Try filling the data manually through phpMyAdmin if you’re interested to see the result if the data is not empty.

Route::get('/', function () {
    dd(Post::all());
});

Controllers

After understanding routes and model, you’ll feel that the route will get very cluttered if the function is complicated. That’s where controller comes in.

A controller is where you place most of your application login. It is a Class that has functions in it for your application logic. For example, you can create a function to replace what we did before (showing the data from database).

Run this command first to create the PostController. For convention, you usually create a controller based on a model.

php artisan make:controller PostController

Then modify the code inside. Don’t forget to include the Post model.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        dd(Post::all());
    }
}

To try it out, go to web.php, include the controller and replace the function with the PostController’s index function.

use App\Http\Controllers\PostController;

Route::get('/', [PostController::class, 'index']);

It will have the same result as before, but the route is much cleaner, isn’t it?

MVC

Now you’ve learned about models, views and controllers. Together, they form a concept called MVC (Model View Controller). It is a pattern in software design that separates data, UI and logic to make the code cleaner and easier to maintain with this “separation of concerns”.

You’ve seen how they work together smoothly forming a pattern.

MVC is a common pattern in frameworks and is a very useful concept to keep the code maintained.

Workflow

The workflow I use is in the same order I explained the concepts above.

First of all, I edited the .env

Then, say I want to create a form to add a post. I’ll create the necessary routes, views to show the form. Keep in mind that the views are still static (not able to show data).

After that, I’ll create a table with migrations as well as the model for it.

Finally, I’ll create a controller for the logic and modify the views to show the data (make it dynamic).

Just repeat that workflow until the application is done.

Tips

If you need quick description of what each php artisan command does, just run php artisan on your terminal and you’ll get a list of commands with their descriptions.

I showed you the basics you need to understand to build an application. Of course, Laravel has much more capabilities than what I showed. For example, there are Middleware, Seeders, I haven’t showed you how to use POST method, etc. You can always rely on Laravel’s documentation for reliable references.

With ChatGPT, making Laravel application has been easier than ever. You ask it to make or explain a code for you. You want to add comments? ChatGPT can do it for you. But, of course, ChatGPT isn’t meant to build a complete app for you. You still have to do it, ChatGPT is just here to help make it easier for you.

Common Questions

Now you’ve understood the basic concepts. Here are some common questions about Laravel.

What is Laravel used for?

Laravel is usually used for building custom web apps. It can handle full stack applications, Single Page Application (SPA with Vue, React, etc), APIs, admin panels, e-commerce and many more. You can build those applications more quickly and efficiently using Laravel than using vanilla PHP.

Is Laravel easy to learn?

Laravel is relatively easy to learn if you have the understanding of PHP and MVC. Those two are the key points to learn Laravel.

You need to understand the syntax of PHP and preferably be able to build a CRUD application with PHP. MVC is also necessary as it is the main concept of the Laravel framework, but you can learn it along the way.

I suggest you at least understand PHP before learning Laravel. Overall, Laravel is relatively easy to understand.

Is Laravel frontend or backend?

Laravel is a backend framework as it mainly provides server-side capabilities such as manipulating the database. However, Laravel also gives a full stack experience, you can build the front end with blade, Livewire or even your favorite JavaScript framework (Vue or React) through InertiaJS.

Conclusion

Now you understand the basics of Laravel. To recap, Laravel is a PHP framework that uses MVC concept and comes with robust features. It is very useful if you want to build a web application. If you get comfortable with it, you can build web applications quickly.

Next, we’ll learn how to build a CRUD (Create, Read, Update, Delete) application with Laravel.

Leave a Comment