Laravel Starter Guide: Part 2 – Basic Concept (MVC)

laravel starter guide basic

Laravel is a FREE, Open-Source PHP Web Framework. It is created by Taylor Otwell. It follows the Model, View, Controller (MVC) architecture. The websites built in Laravel also secure. It prevents the many attacks that can take place on the website. In this tutorial, we focus on laravel basic concepts.

Laravel Starter Guide: Laravel Tutorial (Part 1)

Laravel Basic Concept

What is MVC?

Model – This component used for the define our database tables and organize data.
View – This component contains the UI logic in the Django architecture.
Controller – This component handles the user interaction and selects a view according to the model.

Laravel Basic Concept – Models

All the models are stored in the “app” directory. (ex: User.php)

laravel guide

Laravel Basic Concept – View

All the views are stored in the “resources/views” directory.

laravel guide

What is Blade Template?

Blade is the powerful templating engine. It does not restrict us from using plain PHP in our views. Blade view files use the .blade.php file extensions.

[name].blade.php

Example code: welcome.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

               <!-- ...CSS... -->

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Docs</a>
                       <!-- ...Links... -->
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>
laravel starter guide basic

Laravel Basic Concept – Controllers

All the Controllers are stored in the “app/http/Controllers directory.

laravel starter guide basic
laravel starter guide basic

Work with MVC

Creating Views

First, navigate the “resources/views” directory and create a new file with .blade.php extension. Now add some HTML here.

about.blade.php

<!-- about.blade.php -->

<html>
    <head>
        <title>About us</title>
    </head>
    <body>
        <h1>About us</h1>
        <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam inventore, in commodi debitis eum fugit perferendis numquam corporis deleniti id velit magnam ipsa mollitia dolorum dolore doloremque? Asperiores, quam adipisci?
        </p>
    </body>
</html>
laravel starter guide basic

HTML Tutorial: Introduction for beginners (Basic)

Create Routes

Laravel routes are defined in route files, It located in the routes directory.

laravel guide

Basic

Route::get('{route}', function () {
    return view('{locationOfView');
});
laravel starter guide basic

The routes/web.php file defines routes that are for our web interface. so, open web.php file and enter following code to add “/about” route to our blog

Route::get('/about', function () {
    return view('about');
});

/* 
Route - http://127.0.0.1:8000/about
View - about.blade.php {resources/view/about.blade.php}   
*/

Then visit http://127.0.0.1/about

laravel guide example

Creating Controllers

First, navigate the “app/Http/Controllers” directory and create a new file with .php extension. Now add following code to create PageController.

PageController.php

<?php
/* PageController.php */

//namespace App_name\Http\Controllers;
namespace App\Http\Controllers; 
use App\Http\Controllers\Controller;

class PagesController extends Controller
{
    public function getContact() {
        return "<h1>Contact me</h1>";
    }

    public function getAbout() {
        return view('about');
    }
}

?>

Then Update Route (routes/web.php)

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('about', 'PagesController@getAbout');
Route::get('contact', 'PagesController@getContact');

Then visit http://127.0.0.1/contact and http://127.0.0.1/about

laravel guide example

Passing Data to a View (Variables)

Update PageController.php

<?php
/* PageController.php */

//namespace App_name\Http\Controllers;
namespace App\Http\Controllers; 
use App\Http\Controllers\Controller;

class PagesController extends Controller
{
    public function getContact() {
        return "<h1>Contact me</h1>";
    }

    //Updated
    public function getAbout() {

        $name = "George"; //Variable 1
        $website = "https://ctechf.com"; //Variable 2

        return view('about')
            -> with('name', $name)
            -> with('web', $website);
    }
}

?>
laravel starter guide basic

Update about.blade.php

<!-- about.blade.php -->

<html>
    <head>
        <title>About us</title>
    </head>
    <body>
        <h1>About us</h1>
        <p><b>Name:</b> {{$name}}</p>
        <p><b>WebSite:</b> {{$web}}</p>
    </body>
</html>
laravel starter guide basic

Passing Data to a View (Arrays)

Update PageController.php

<?php
/* PageController.php */

//namespace App_name\Http\Controllers;
namespace App\Http\Controllers; 
use App\Http\Controllers\Controller;

class PagesController extends Controller
{
    public function getContact() {
        return "<h1>Contact me</h1>";
    }

    //Updated
    public function getAbout() {

        $name = "George"; //Variable 1
        $website = "https://ctechf.com"; //Variable 2

        $data = []; //Array
        $data['name'] = "George";
        $data['web'] = "https://ctechf.com";

        return view('about')
            -> with('data', $data); //You can use ->withData($data)
    }
}

?>
laravel starter guide basic

Update about.blade.php

<!-- about.blade.php -->

<html>
    <head>
        <title>About us</title>
    </head>
    <body>
        <h1>About us</h1>
        <p><b>Name:</b> {{$data['name']}}</p>
        <p><b>WebSite:</b> {{$data['web']}}</p>
    </body>
</html>
laravel starter guide basic
laravel guide example

Creating Model

Enter the following command. it will create the Post model

php artisan make:model Post

model -> Post.php

laravel starter guide basic

Creating Migration

Enter the following command. it will generate the migration

php artisan make:migration create_posts_table
laravel starter guide basic

migration files stored in the “database/migrations” directory.

migration -> 2019_07_24_114124_create_posts_table.php

laravel starter guide basic

Database Migration

laravel starter guide basic

Available Column Types

$table->increments('id'); //Auto-incrementing
$table->binary('data'); //BLOB 
$table->char('name', 100); //CHAR
$table->boolean('confirmed'); //BOOLEAN
$table->json('options'); //JSON
$table->string('name', 100); //VARCHAR
$table->text('description'); //TEXT

more details: https://laravel.com/docs/5.8/migrations

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');

            //Enter additional Column here
            $table->string('title', 100);
            $table->string('author', 100)->default("admin"); //Specify a "default" value for the column
            $table->text('content');
            $table->string('link')->unique();

            $table->timestamps();
        });
    }

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

Then enter the following command to migrate the database.

php artisan migrate
laravel starter guide basic

Index Lengths & MySQL / MariaDB – [Fixing: PDOException::(“SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes”) error]

laravel starter guide basic

If you got this error while migrating. drop existing tables in your database. Then edit your AppServiceProvider.php file and inside the bootmethod set a defaultStringLength

Schema::defaultStringLength(191);

Complete Code:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}
laravel starter guide basic

Now run the migration.

Database:

laravel guide mysql

Sources : 
https://pixabay.com/ (images) 
https://laravel.com/docs/5.8/ (Documentation)

Hello Friends,

Hope this post (Laravel Starter Guide: Laravel Tutorial Basic (Part 2)) will help you to learn something, If you enjoy my work then please share my posts with your friends and anyone who might be interested in programming and web developing. Please don’t forget to subscribe my mailing list.

If you had any problem with this post, please do mention it in the comment section.

Like CtechF Facebook fan page: https://www.facebook.com/ctechf

Best Free eBooks to Learn Python Programming

python

Free eBooks to Learn Python, Here are 13 of the best Python eBooks for python lovers.
Download Now

What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python
Python Tutorial: Django Tutorial for Beginners

How to be a Programmer

Leave a Reply

56 Shares
Share
Tweet
Share
Pin
Share