Hazem Allbabidi

January 14, 2024 | 9 min read


Laravel in Less Than 10 Minutes

Laravel is an opinionated PHP framework that provides almost all of the necessary parts to build a secure and organized Web application or API.

It provides you with all the necessaties to build your application. From an ORM, to File Management, to even Unit Testing, it has all the features any web developer would require to build and deploy a web application without any hassle.

In this article, I will be going through what Laravel is, what features it provides, and why to use it when there are tens of other back-end frameworks out there.

PHP in the 2020s?

While a lot of web developers will tell you that PHP is outdated, Laravel has kept it alive and well. PHP is the programming language used within Laravel. Everything you see in the framework was built using PHP.

Many companies, especially start-ups, still use PHP as their main web-development programming language, and one of the main factors of it is that they use Laravel due to how easy and simple it is. As of the beginning of 2024, over 40,000 companies use Laravel as their main web development framework, and they even have over 75K stars on Github.

Laravel Is An MVC

MVC is short for Model-View-Controller. It is a type of architecture that is divided into three main parts:

Models are the representation of the tables in a database. For example, let us say you have a table in the database titled “Users”. This table has columns for the first name, last name, email, and password. A model is created to represent this table, the model file would be titled “User” which represents a single user. This model file allows for the viewing and manipulation of the user data. The file describes what columns can be edited and what data-type is assigned to each column (if necessary), such as if a column is a timestamp. The file also includes any “relationships” that exist between this model and another. For example, if a user has posts, then there would be a relationship between these two models in which the relationship describes that the user can have many posts. This relationship happens with the help of the foreign key constraint in the database.

Views are the UI files that the user would see in the Front-End. While Laravel is mostly used for the Back-End, they offer a way to build a GUI to be accessed by the users of the system. The Views are files that include all the pages that the user would access, such as a Login Page, a Home Page, and more.

Controllers are the middleman between the Model and the View. Controllers are classes that include functions that are responsible for handling any user input or data to be saved in the database, or to be sent to the Front-End. Controllers are usually the files that include the business logic of an application. For example, we could have an Authentication Controller that has a Login function. The controller allows us to tell the Login function which inputs to take from the user, such as the email and password, and what to do with them (e.g. authenticate the user).

What Features Does It Offer?

Laravel offers various features and tools to make the development of most web applications very simple.

They offer an ORM called Eloquent which allows you to work with the database in a more human-friendly way. Instead of writing SQL queries, you can use simple functions to access, update, or delete any data in the database.

Laravel also offers a templating engine called Blade to have your own Front-End using Laravel. It allows you to use custom Laravel or PHP syntax to display data in the User Interface.

It provides many more features as well, such as built-in Hashing and Encryption, File Management, Queuing, Notification Management, Migrations to keep track of all the changes made to the application database, and lastly, a tool called Artisan which allows you to create Controllers, Models, Migrations, and more, by running simple commands in the terminal.

Building Your Own Laravel API

In this next section, we will be building a very simple API using Laravel

The API will be a simple Customer management system where we can view all customers in the system, as well as create a customer.

Prerequisites

In order to complete this tutorial, you will need the following:

Setting It Up

In order to start using Laravel, we first need to install Composer, which is a dependency manager used in Laravel.

We can do that by running the following in the command line:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

You then need to make the application globally accessible. On Linux, you can run the command below:

sudo mv composer.phar /usr/local/bin/composer

To confirm it works fine, run:

composer --version

This should print out the installed version of Composer.

Next, we need to create a new Laravel project. You can do so by running:

composer create-project laravel/laravel example-app

This command creates a Laravel project with the name example-app. You can change the name before running the command.

Creating The Model, Controller, and Migration Files

We can use the utility tool Artisan to create the necessary files.

First, we will create the model. We can do that by running:

php artisan make:model Customer

Next, let us create the migration for the database table:

php artisan make:migration create_customers_table

The names of the files for migrations have a naming convension: create_ describes the task of this file, which is to create. Then, we add the name of the table customers and lastly, we describe what we are creating/altering, which is a table.

Lastly, we will create the controller:

php artisan make:controller CustomerController

Configuring The Database & Migrating The Database Files

Before we can continue, we have to plugin the database. We can do that by copying the .env.example and creating a new file called .env.

Next, we need to add the database access details in the .env file, in the section shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Change the details as appropriate.

Next, we need to create a key for this application:

php artisan key:generate

Finally, run the command below to cache the details in Laravel:

php artisan config:cache

Before we can migrate the Customer table. Let us add some values. Open the files and edit the up function:

Schema::create('customers', function (Blueprint  $table) {
	$table->id();
	$table->string('name');
	$table->string('email');
	$table->timestamps();
});

We are creating a table customers with the columns ID, Name, Email, and the timestamps which keep track of when the customer was created or last updated.

Next, we can migrate the database files to create the necessary tables by running:

php artisan migrate

Note: if you do not already have the database created, you will be asked if you want to create it, choose “Yes”.

Now we can move on to editing the model.

Editing The Model

All we need to do here, is tell Laravel which columns in the database table can be edited. We can do so by adding the following lines inside the class:

protected  $fillable = [
	"name",
	"email"
];

This tells Laravel that we can edit the Name and Email fields.

Editing The Controller

This is where most of the magic happens. We will be writing a function that returns all the Customers in the database and a function that creates a Customer.

Before we start, we need to include the Customer model file in the controller. Open the CustomerController file and add the following line right below the namespace line near the top:

use App\Models\Customer;

Now, we will create a function that returns all the Customers. Add the following lines inside the class:

public  function  index() {
	return  response()->json([
		"customers" => Customer::all()
	]);
}

We created a function called index which returns a JSON response. The JSON response includes the customers data. We retrieve all of the customers using the model: Customer::all().

Next, we can make a function to create a customer:

public  function  store(Request  $request) {
	$customer = new Customer([
		'name' => $request->input('name'),
		'email' => $request->input('email'),
	]);

	$customer->save();

	return response()->json([
		"customer" => $customer
	]);
}

This function called store takes the input from the user through the POST request data, creates a customer, stores it in the database ($customer->save()), and returns it back to the user with the newly-assigned ID.

Adding The API Route

To be able to use the new functions you created, go to the api.php file located in the routes file, and add the following lines at the end of the file:

Route::prefix('customers')->group(function () {
	Route::get('/', [CustomerController::class, 'index']);
	Route::post('/', [CustomerController::class, 'store']);
});

Note: Make sure to import the controller file at the top of the file, right below the <?php:

use App\Http\Controllers\CustomerController;

Here, we created a group of routes starting with the path customer. Below it, we added two new routes. The first being the function that returns all of the Customers that we created the controller. Keep in mind that it is a GET request.

Next, we added a POST request route for creating or “storing” the customer.

Testing

In order to test the requests, we need to start the development server. We can do that by running:

php artisan serve

It should display a message telling you on which port it is running. Usually, it would be running on localhost and on port 8000.

To test the routes, We can open Postman to test the routes. Create a new request in Postman and in the URL type localhost:8000/api/customers and in the Headers section, add two headers. The first header is the Content-Type with the value is application/json, the second header is the Accept with the value is application/json. Now, send the request and see the output:

{
	"customers":  []
}

To test out the Create function, duplicate the previous request, change the request type to POST. Then, open the Body section, choose form-data and add the two keys name and email along with a value for each one. Send the request and you should see an output like the one below:

{
	"customers":  [
		{
			"id":  1,
			"name":  "Hazem Hadi",
			"email":  "hazem@hadi.com",
			"created_at":  "2024-01-13T16:14:41.000000Z",
			"updated_at":  "2024-01-13T16:14:41.000000Z"
		}
	]
}

Now go back to the first tab and retrieve all the customers. You should see a similar output:

{
	"customers":  [
		{
			"id":  1,
			"name":  "Hazem Hadi",
			"email":  "hazem@hadi.com",
			"created_at":  "2024-01-13T16:14:41.000000Z",
			"updated_at":  "2024-01-13T16:14:41.000000Z"
		}
	]
}

Conclusion

Laravel is one of my personal favorite frameworks to use on the Back-End, due to how it simplifies even some of the most annoying tasks. I used it on multiple projects to fit different needs and using some different packages as well.

Thank you for reading this article and tutorial. I hope you learned enough about Laravel that you are more encouraged to use it for a real project.

See you in the next article!


Previous

Git in Less Than 10 Minutes

Next

Book Lessons: The Pragmatic Programmer
Sign Up To Binance To Get 10% Off Commission Fees Sign Up To Kucoin