How does laravel framework work?

Laravel is very popular MVC framework written in php language. It is pretty easy to learn and it is an open source. Followings are some of the advantages of using laravel:

  • Easy to learn and uderstand
  • Comes with built in features like authentication, job scheduling, mailing, event management, mvc etc..
  • Secure and prevents xss, sql injections and some other known vulnerabilities.
  • Using tools as memcached or redis you can boost the web app performance
  • Comes with build in user auth management feature
  • It uses blade template engine which uses a simple syntax to write html code
  • It has good database migration mechanism
  • It follows MVC concept which can help separate business logic easily. You can also write modular or multi-tenant apps.
  • It is easy to create multi-language web apps
  • It comes with a great feature like task scheduling which helps you manage your background jobs easily using database or redis queue system

How do I get started with laravel?

In this tutorial we will create a sample blog application step by step so that you know how to get started with laravel.

Let say we want to create a two page blog application. When user visits our website he first sees lists of all blogs. When he clicks one of the blog title he will be then taken to that blog page where we show him additional information.

Fist we need to decide the url that user will be typing in their browser. Let say we want to create following two urls.

  • GET /
  • GET /post/sample-post

Installing Laravel and setting up Routes

It is very important that you decide url along with their http method so that you know weather it is a read, write, update or delete operation. If you do not know more about http methods please read my tutorial on laravel routing.

Laravel Routing

Next, once we decided urls its time to install laravel on our local environment. Please follow my tutorial on laravel installation.

Laravel Installation

Alright, now we have laravel project on our local environment. First thing we want to do is to define our routes in routes/web.php file. Open this file and add following two routes.

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

Now, we added routes however we need to define controllers now and methods that our routes depends on them. Open up your terminal window and run following command to create a new controller.

php artisan make:controller PostController

Now, we will add index and show methods in our newly created PostController

<?php

namespace App\Http\Controllers;

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

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

Alright, we added two methods that our laravel route depends on and also notice that your controller returns index and post views. So we need to define these views in resources/views folder.

Create following two view files in resources/views folder:

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

Now, when you hit your browser at http://127.0.0.1:8000 you will see a blank page.

Creating Migration File

Next, now that we have our route, controller and view files we need a database to add some data. I assume that you have mysql server running on your local environment. Let's update our .env  file in our laravel project to reflect our mysql server settings.

Update following configurations according to your mysql server credentials:

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

Now, we are ready to create our first migration file. For our project we need to create a post table in our database. Open your terminal window and run following command to create your first migration.

# 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

Above command will create a migration file under database/migrations folder. Open newly, created migration file and update with following contents.

<?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');
    }
}

Basically, we are creating a post table with some columns that we will need for our test app here. Once we have this changes update we will run following command to create a table in our database.

Open your terminal window and while being in project root directory run following command:

# run following command to create a table
php artisan migrate


# sample output of above command
Migrating: 2019_12_16_160633_create_post_table
Migrated:  2019_12_16_160633_create_post_table (0.03 seconds)

Now, if you check your database you will see a new table called post is added. Next, we will need some sample test data to play with. 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 until advised. It may wipe out all existing data each time you run the seeder.

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

# create a new seeder
php artisan make:seed PostTableSeeder

Above command will create a file in database/seeds  folder open newly created seeder and add 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),
            ]);
        }
    }
}

Cool, now that we have our seeder ready we need to let laravel know about our new seeder. Open database/seeds/DatabaseSeeder.php  file and add a new line as shown in below code:

<?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 following command on your terminal window to apply our seeder which will create 100 records in our post table.

php artisan db:seed

Above command will create sample 100 records in your database. Let's now create our Post model so that we can use this newly created model in out controllers to fetch data from the database.

Run following command on your terminal window to create a new model

php artisan  make:model Post

Open your HomeController.php file located in app/Http/Controllers/PostController.php and add following code. Basically, we want to list all posts from the database via our post model and pass this data to our view file for display purpose

<?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
        ]);
    }
}

Alright, no 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 displayed on our browser.

First of all 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>

Alright, basically we are looping through posts variable that we passed in PostController index method and looping through it and displaying our blog 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>

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

What did you learn?

Throughout this tutorial you have learned following things.

  • How to create Model, View and Controller
  • How to create and run database migration
  • How to create and run database seeder
  • How to fetch data from the database and display

You can download full source code for this tutorial below. Thank you.

Download Source Code