Simple Laravel guide for beginners

Laravel is a popular PHP framework following MVC architectural pattern. I am composing this Laravel guide for absolute beginners and will try to explain the basic concepts of the framework such as model, view, controller, migration, routes, etc. We will learn all these basic concepts using a simple example of Posting product’s data to our database. So let’s get started.

Setup Laravel project

First thing first! create and setup a new Laravel project. I already have a detailed guide on that. Execute the following command to install Laravel using composer.

composer create-project laravel/laravel projectname

It will take a while to create a Laravel project for you. Open the project in your preferred code editor.

Next you need to create a database for your project. Once database is created, setup the connection with the database in the .env file. That’s it we are ready to start working on our beginners guide for Laravel.

//connect database in .env file 
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=productapp
DB_USERNAME=root
DB_PASSWORD=

What is a Model in Laravel?

Before creating a model let’s first discuss what Model basically is? Since I already mentioned, Laravel in an MVC framework where ‘M’ stands for Model. A Model in Laravel represent a database table where model name is always singular and it’s corresponding table is plural .e.g. a Product model will represent products table in the database.

Laravel provides eloquent ORM(object relational mapper) which is a simple, quick and easy way to query data from database using Models. So, Model will help us interact with our database which makes database operations easy and fast.

To create Model, we need to write an artisan command as follows.

php artisan make:model Product

Artisan is Laravel’s command line interface which provides a bunch of artisan command to create ease in development.

Now when you go inside your project App\Models\Product.php , you will find your Model class which looks something like this.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
}

We have Product class which extends Laravel’s Model class and it uses a hasFactory trait. In Laravel, we will be using classes and traits all the time. In languages that only supports single inheritance, we have the concept of traits which is just like class but it’s purpose is just to group functionality for reusability. Traits can’t be instantiated like classes.

What are migrations in PHP Laravel?

In Laravel, we don’t create database tables manually. Instead, we use migrations to specify our database table schema. To create migrations, we have the following artisan command.

php artisan make:migration create_products_table --create=products

Inside database\migrations directory, you will find your migration file containing two method up() and down(). When we run php artisan migrate command, the up() method will create the table in our database and when php artisan migrate:rollback command is executed, down() method reverses the migration. The code of our migration file will looks something like this.

<?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('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->float('price');
            $table->timestamps();
        });
    }

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

Run the php artisan migrate command to create tables in database.

What is a controller in Laravel project?

Next, we will need to create a controller to write our business logic. A controller groups logic related to handling a specific request into a single class. All the logic of Product related requests will be grouped inside our ProductController. To create controller, we need to execute the following artisan command.

php artisan make:controller ProductController

Now see your project’s app\Http\Controllers directory and see a new ProductController.php file created there.

Note: You can create migration and controller when creating Model by passing options in the command shown as below.

php artisan make:model Product --migration --controller
//or simply write 
php artisan make:model shop -mc

Such commands save plenty of time when working on real projects.

Now write a createProduct() function in ProductController which will return our create product form view. We will also need one storeProduct(Request $request) function to store the form request data into database. We will discuss about views in the next section of the article. For now, it’s the frontend of our Laravel application. Now see how our controller code looks like after writing these two functions. Since it’s Laravel beginners guide, that why I am not covering complex concepts like request validation.

<?php

namespace App\Http\Controllers;

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

class ProductContoller extends Controller
{
    public function createProduct(){
        return view('product.create');
    }

    public function storeProduct(Request $request){

        Product::create($request->all());
        return redirect()->back()->with('message','product added successfully');
    }
}

The createProduct() function is returning create.blade.php view file placed inside a product folder inside resources\views directory. When returning views, we don’t need to write file extensions. When view files are placed inside some folder in resources\views, we write the folder name, dot and then the view file name shown as follows return view('product.create').

The second storeProduct(Request $request) function receives form request as a parameter and store it into database using Product model. The eloquent create function is used to store the request data into database. Then the user is redirected back with a session message.

What are View in Laravel applications?

Views determines the frontend of your Laravel application. It’s simply the HTML code to render web page design of your application. When user hits a route in web browser, the route either handles the request itself or forwards it to a controller function. Afterwards, a relevant view is returned with any required data. In next section, we will discuss routes in detail. Laravel has blade template engine which provides blade directives to make handling dynamic data easy in view files. In Laravel, we create frontend files in resources\views directory.

<!doctype html>
<html lang="en">

<head>
  <title>Title</title>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS v5.2.1 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

</head>
<body> 
<div class="container mt-4">
    @if (Session::has('message'))
        <div class="alert alert-success" role="alert">
            <strong>Alert</strong> {{Session::get('message')}}
        </div>
    @endif
    <div class="row">
        <div class="col-6">
            <form action="{{route('storeproduct')}}" method="post">
                @csrf
                <div class="mb-3">
                    <label for="title" class="form-label">title</label>
                    <input type="text" name="title" id="title" class="form-control" placeholder="Enter product title">
                </div>
                
                <div class="mb-3">
                    <label for="price" class="form-label">price</label>
                    <input type="number" name="price" id="price" class="form-control" placeholder="Enter product price">
                </div>
                
                <div class="mb-3">
                    <label for="" class="form-label">Description</label>
                    <textarea class="form-control" name="description" id="description" rows="3" placeholder="Enter Product 
                     Description"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

In above shared example, we have a simple view file create.blade.php. It contains HTML markup of a form. It is using bootstrap classes for styling. What’s new in this file is the {{route('storeproduct')}} curly braces and @if @endif. In core PHP, we write dynamic PHP like this. <?php $exampleVariable ?>. But in Laravel, it’s equivalent syntax is the pair of curly braces like this {{$exampleVariable}}. The @if @endif are blade directives providing simple and quick syntax for if statement. Read Laravel blade docs for detail understanding.

What are routes in Laravel app?

In Laravel, we create the request URL using routes and it’s not the name of exact file on web application. In core PHP we do it using exact file names which is neither user nor search engine friendly. Routes are to be specified in routes\web.php file. As we already discussed in the view section of the article, a route can either handle request itself or forwards it to a specific controller function when a specific route is hit in the browser. Then a response is return to the user’s request.

<?php

use App\Http\Controllers\ProductContoller;
use Illuminate\Support\Facades\Route;

//route handling request itself by accepting a closure
Route::get('/', function () {
    return view('welcome');
});

//route forwarding request to ProductController
Route::get('createproduct', [ProductContoller::class,'createProduct']);
Route::post('storeproduct',[ProductContoller::class,'storeProduct'])->name('storeproduct');

We have two custom routes described as follows. The createproduct is an HTTP get method route which forwards request to createProduct() function and it returns create.blade.php view. Then we have storeproduct HTTP post route which forwards request to storeProduct(Request $request) function which receives the form request through post method and store the form request data into database. That’s the end of simple Laravel guide for beginners. the output screenshot is shared below.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top