Build the Laravel Application as Pro for Beginner — Part 1

Chiragkumar Patel
9 min readOct 6, 2021

We will talk about how to start with the Laravel application by adding crucial composer packages with a repository pattern.

Laravel is the open-source framework that is growing faster in web application development as it provides several features like dependency injection, queues, event broadcasting, etc.

Let’s begin with the boilerplate concept. What do you mean by boilerplate? In simple terms, it is pre-installed code to start the application quickly and easily. We will do the same by installing the various package and a few coding concepts. Later on, a developer can follow the same concept for further coding.

Here are the steps that we will be going through to build a basic boilerplate.

  1. Laravel Installation.
  2. Authentication
  3. Repository pattern with details example.
  4. Crucial Composer packages
  5. Conclusion.

1. Laravel Installation

As per the Laravel documentation, We can create a new application project using the composer command shown in below figure 1.

Figure 1

Next, we will go to the project folder and find the .env file to set up the database connection. Please check the below screenshot. For database connection, you must require MySQL that can come in handy with XAMPP for Windows, MAMP for Mac, and for Linux, you have to install through the command line. I am not going into depth with the installation.

Now we will start the application by running the “PHP artisan serve” command. This command will start Laravel’s local development server. Due to this command, we don’t require any other local development environment like XAMMP or MAMP (MYSQL purpose using it). As shown in below figure 2.

Figure 2

2. Authentication

There are several packages are available in the Laravel documentation. We can use any of those packages to build a robust and reliable application. I am not going to discuss all packages as you can go to the Laravel website and look for the packages section for detailed understanding. To head start of any application, Authentication is a must.

Let’s go through vivid packages and their usage in the authentication.

2.1 Laravel Fortify

An ideal scenario to use this package is for backend development. If you wish to build your application for a backend development purpose then this is the best package to use for Authentication. It has features like — Login, Register, Email Confirmation, and Reset Password. Check this package by going through this link — https://laravel.com/docs/8.x/fortify

  1. Let’s install Laravel Fortify as shown in Figure 3.
Figure 3 — Installation of Laravel Fortify

2. Publish Fortify’s resource by running the below command. As you can see that it is creating a folder called app/Actions along with configuration and migration files.

Figure 4 — Vendor Publish for Fortify

3. Finally, run the migration command as shown below. All steps are also given this link so you can refer it — https://laravel.com/docs/8.x/fortify#installation

Figure 5— Running migration

4. Run the artisan serve command to check the Laravel application welcome as shown below.

Figure 6— Welcome page

5. To use the authentication service, we need to create blade templates for Login, Register, etc. Here I have created a two-blade template called login.blade.php and register.blade.php (Folder — resources/view/auth/login.blade.php and resources/view/auth/register.blade.php). Please check the below code.

Figure 7— Register.blade.php
Figure 8 — Login.blade.php

After this package installation, we don't need to worry about the controllers or routes for this package because it is inbuild functionality. Just need to link up with App\Providers\FortifyServiceProvider. Please have a look at the below screenshot.

Figure 9 — Connecting the register view and login view.

In figure 9, It is showing that we have registered views with login.blade.php and register.blade.php. In this article, I am going to show you only register and log in. For further implementation like reset password and email verification, you can take the reference of login and register to achieve the same thing.

2.2 Laravel Passport

Laravel Passport is the package that is used for API authentication and built based on the OAuth2 (Authentication protocol) concept. It provides the authentication for APIs by providing the token. If the token is valid then it will allow to access the APIs.

  1. To get started, we can install this package using composer. Here is the command for it.
composer require laravel/passport

2. After that, we need to run the migration command and passport install as shown.

php artisan migrate
php artisan passport:install

2.3 Laravel Sanctum

Laravel Sanctum is a crucial package that provides the authentication for SPA (Single page application — Could be any front end application build in React, Angular, or any other front end technology), token-based APIs, and mobile applications.

  1. To get started, follow the below command to install the package.
composer require laravel/sanctum

2. After that, run the migration and configuration files as shown below.

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"php artisan migrate

3. Understanding of MVC and Repository Pattern

In the Authentication section, we did login into the system successfully. Next, we will be going to discuss the Repository pattern implementation. Let’s understand the MVC pattern first before jump into the Repository pattern.

Note: This is just understanding purpose, I am showing the MVC pattern so it could be easy to understand the how repository pattern little bit different from the default pattern.

Figure 10 — MVC Pattern

Laravel is built on the MVC architecture pattern to head start to any project quickly. Here in figure 10, MVC flows are shown.

URL Request — When the user hits any request, it goes to routes.

Controller — Redirect toward respective controller, where business logic checks. The controller is going to request a few data information from the Model.

Model — This is going to fetch the requested information from the database and send it back as a response to the controller.

View — It renders the final information provides by the controller.

Now let’s back to the current section.

Repository pattern — In simple terms, it is the middle layer between the business logic (Controller) and data sources (Model layer). Repositories are classes that would contain the logic required to access database information.

Fig 11 — Repository pattern

Benefits -

  1. Loosely coupling between model and controller
  2. Data abstraction to access data resources.
  3. Avoid repetition of code
  4. Easy way to test the application using unit testing.

Repository pattern with detailed example.

Let’s create To-do CRUD. To perform the to-do operation, we need to create a migration file to create a database.

Fig 12 — Created migration file
Fig 13 — Added the field migration file.

Next, it will create a table by running the migration command as shown below.

Fig 14 — the table is created in the database.

Let’s create a Todo controller and model as shown below. The — resource param will create CRUD methods.

Fig 15 CRUD methods

As per above fig 11, BaseRepository (This class implements BaseRepositoryInterface.) will have common methods for all crud operations like upserts (update and insert). We can avoid code repetition in CRUD or common functionality. Here is the code.

  1. BaseRepository
class BaseRepository implements BaseRepositoryInterface
{
/**
*
@var Model
*/
protected Model $model;

/**
*
@param Model $model
*/
public function __construct(Model $model)
{
$this->model = $model;
}

public function upserts(Request $request, int $id = null): bool
{
$todo = new $this->model;
if ($id !== null) {
$todo = $this->model::find($id);
}
$todo->task_name = $request->task_name;
if ($todo->save()) {
return true;
}
return false;
}
}

Here is the BaseRepositoryInterface. It is a normal interface and you can notice here that we are using some of the good features of PHP 7.x such as Type Properties, Scalar Type, and Return Type Declarations.

2. BaseRepositoryInterface

interface BaseRepositoryInterface
{
public function upserts(Request $request, int $id = null);
}

Now what to do if we don't have a common method so basically we can’t put those methods in BaseRepository as it is built to serve a common method or repetition of coding. Now we will create another repository to serve different methods which are not common and it will be changed based on the controller (For example, TodoController has TodoRepository and PostController has PostRepository However, few methods are common that will go into BaseRepository).

3. TodoRepository or AnyRepository

declare(strict_types=1);

namespace App\Repository;

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


class TodoRepository extends BaseRepository implements TodoRepositoryInterface
{
protected $model;

public function __construct(Todo $model)
{
$this->model = $model;
}

public function getAll()
{
return $this->model->select('id','task_name')->get();
}

}

As you can see above coding, here I have mentioned getAll() method, which is fetching the specific columns (Id and Task name and another controller it would be changed) information.

4. Controller — Store method

Here we have implemented the store method for adding and updating the task information.

class TodoController extends Controller
{
private TodoRepository $todoRepo;

public function __construct(TodoRepositoryInterface $todoRepository)
{
$this->todoRepo = $todoRepository;
}

/**
* Display a listing of the resource.
*
@return Application|Factory|View
*/
public function index()
{
$todos = $this->todoRepo->getAll();
return view("todo.index", compact(['todos', $todos]));
}

/**
* Show the form for creating a new resource.
*
*
@return void
*/
public function create(Request $request)
{

}

/**
* Store a newly created resource in storage.
*
@param Request $request
*
@return JsonResponse|void
*/
public function store(Request $request): JsonResponse
{
$validator = Validator::make($request->all(), [
'task_name' => ['required', 'string'],
]);

if ($validator->fails()) {
return response()->json(['error' => $validator->errors()->all()]);
}
$this->todoRepo->upserts($request);
return response()->json(['message' => 'New Task is added', 'page' => '/todo']);
}

Above coding, we have injected class dependencies into the controller via the constructor. In the store method, we have validated the inputs then we have to use the upserts function to insert or update the task. Response, we have used JSON because we are calling Ajax.

5. View — Index.blade.php

@extends('layouts.layout')

@section('content')
<p class="m-3">
<button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Add Task</button>
</p>
<table class="table">
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">Task Name</th>
</tr>
</thead>
<tbody>
@if(!empty($todos))
@foreach(
$todos as $todo)
<tr>
<th scope="row">
<button data-id="{{ $todo->id }}" class="btn btn-sm btn-info">Edit</button>
<button class="btn btn-sm btn-danger">Delete</button>
</th>
<td>{{ $todo->task_name }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Task</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<label for="task_name" class="form-label">Task Name</label>
<input required type="text" class="form-control" id="task_name" placeholder="Task Name">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" onclick="add()" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
@endsection

@section("custom_script")

<script type="text/javascript">
function add() {
$.ajax({
type: "POST",
data: {'task_name': jQuery('#task_name').val()},
url: "{{ route('todo.store') }}",
dataType: 'json',
success: function (data) {
if (data.message) {
toastr.success(data.message)
setTimeout(function () {
window.location.href = data.page;
}, 2000);
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
var errorString = '<div>';
errorString += '<p>' + response.error + '</p>';
errorString += '</div>';
toastr.error(errorString)
}
});
}
</script>
@endsection
Adding and displaying tasks

In the same way, you can perform the edit and delete operations. This is an opportunity for you to perform edit and delete operations. I will start to work on part 2 of this article.

Finally, Here is the part 2 — https://medium.com/@chirag1162/build-the-laravel-application-as-pro-for-beginner-part-2-a0c39bb00bee

--

--

Chiragkumar Patel

Gained experience in LAMP Stack and especially in Laravel. Also expertise in Python and R. MSc Artificial Intelligence Student at University of Stirling.