How does Laravel framework work?

Laravel is a popular MVC (Model View Controller) architecture framework written in php programming language. It is an is an open source framework and pretty easy to learn. Followings are some of the advantages of using Laravel:

  • Easy to understand and learn.
  • Has many built in features like mailing, authentication, job scheduling, event management, etc.
  • Secure and prevents xss, SQL injections and some other known vulnerabilities.
  • Uses tools like Redis or memcached to boost web app performance
  • Has build in user authentication management feature
  • Makes use of blade template engine which uses a simple syntax to write html code
  • Supports an amazing database migration mechanism
  • It follows MVC concept which can help separate business logic easily.
  • Uses a MVC structure that helps support separate business logics.
  • Supports writing modular and multi-tenant applications.
  • Helps easily create multi-language web applications
  • Has amazing features like task scheduling that helps manage background tasks and easily create database and Redis queue system.

How to start working with Laravel?

Let’s learn it by creating a simple sample Laravel Blog application following a step by step procedure to know well about Laravel.

For example we want to create a two page blog application. When a user first visits our website he sees a list of all articles. When he clicks one of the article’s title, he will be taken to that article’s page where we show him the additional information about that article.

Firstly, we need to decide the URL that a user will type in their browser. We need to create the following two URLs.

  • GET /
  • GET /post/sample-post

Laravel Routes Set up

A very important step to connect the MVC structure through Laravel Routing. This comes up with a HTTP method that decides whether to do a read, write, update or delete operation.

You will then have your Laravel routes listed in the routes/web.php file, as shown below.

Route::get('', 'PostController@index')->name('post_list');
Route::get('post/{slug}', 'PostController@show')->name('post_page');

We can then create relevant Controllers and Blade files as stated in the routes above.

php artisan make:controller PostController

Next, we will add index and show methods in our newly created PostController. These will display our View (blade) files.

<?php

namespace App\Http\Controllers;

class PostController extends Controller
{
    function index()
    {
        return view("index");
    }

    function show($slug)
    {
        return view("post");
    }
}

The two methods that our Laravel route depends on returns two different views. So we will define these views in resources/views folder.

Create following two Laravel view files in resources/views folder:

  • index.blade.php
  • post.blade.php

You can now navigate to your localhost on browser to run this basic Laravel blogs application.

Create a Migration File

To manipulate with data from database, you will have to create a database migration file. You may assume you have MySQL server running on your local environment.

Firstly, you need to edit your .env file to save your current database credentials.

Update following configurations according as per your MySQL server credentials.

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

You can now create your first migration file. For instance, lets create a posts table in our database. For that, you need to open your terminal and type in the command below.

# Run following command to check your migration status
php artisan migrate:status

# Run following command to create a new migration
php artisan make:migration create_post_table

This creates a migration file under the database/migrations directory of your Laravel project. You may open the file and edit its contents as required.

<?php

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

class CreatePostTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title', 85);
            $table->string('slug', 45)->unique();
            $table->timestamps();
        });
    }

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

So, this creates a post table with some columns that we will test in our app.

Now, in your database you will see a new table called post. Next, we will need some sample test data to play with. So, we will now create a seeder file to load some sample data in our post table.

Seeders are a good place to add some test data in your local environment. Make sure you do not do it on production server until advised. As it may wipe out all existing data each time you run the seeder.

So, open your terminal window again and run following command to create a new seeder.

# create a new seeder
php artisan make:seed PostTableSeeder

The command above will creates a file in database/seeds folder, open the newly created seeder file and add in it the following contents.

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PostTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=0; $i<100; $i++) {
            DB::table('posts')->insert([
                'slug' => $faker->slug(3),
                'title' => $faker->sentence(4),
            ]);
        }
    }
}

Now that we have our seeder ready we need to let Laravel know about our new seeder. For that, open database/seeds/DatabaseSeeder.php file and add a new line as shown in the code below.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(PostTableSeeder::class);
    }
}

Now, run the command below in your terminal window to apply our seeder which will then create 100 records in our post table.

php artisan db:seed

Create a Model

Let’s now create a Post model to use this newly created model in out controllers and fetch data from the database.

Run the command below on your terminal window to create a new model.

php artisan  make:model Post

Open your PostController.php file located in app/Http/Controllers/PostController.php and add following code as shown below. Here, we want to list all the posts from the database via the post model and pass this data to our view file to display it.

<?php

namespace App\Http\Controllers;

use App\Post;

class PostController extends Controller
{
    function index()
    {
        return view("index", [
            "posts" => Post::all()     // gets all the post from the database
        ]);
    }

    function show($slug)
    {
        return view("post", [
            "post" => Post::where("slug", $slug)->first()    // fetch single post with slug
        ]);
    }
}

Now we have our work with our controllers. We need to update our view files so that we can see some data coming from the database and get it displayed on our browser.

Firstly, open resources/views/index.blade.php file and update with following contents.

<h1>Recently created posts</h1>
<hr />
<br />

<ul>
    @foreach ($posts as $post)
        <li>
            <a href="{{ route("post_page", ["slug" => $post->slug]) }}">{{ $post->title }}</a>
        </li>
    @endforeach
</ul>

Here we are looping through the posts variable that we have passed in PostController’s index method to display our posts list.

Finally, we will update our post view file located in resources/views/post.blade.php file with following contents.

<h1>{{ $post->title }}</h1>
<hr />
<br />


<small>{{ $post->slug }}</small>

So, now when you click on any list item on home page it will take you to a post page where we show post title and slug.