Laravel Tutorial Day 4

Learning Objectives: Understanding the use of Controller. As it name says its Controller, so you can manage many things using this Controller. Let’s Make a Controller and see the demo also we will make Login Page and Its verification code using get and post method respectively.


Command to Create Controller in Laravel:
php artisan make:controller NameOfController -i

Once you create Controller, You will find Controller file and then you need to make changes into Route

Route Settings:
use App\Http\Controllers\NameOfController
Route::get(‘/courses’, NameOfController::class)

Now inside the Controller you need to call the View or you can make your customized code there.


If you wish to create Controller for multiple functionalities like Insert, Update, Delete and View, then you have following options in Laravel:

Command to Create Resource Controller in Laravel:
php artisan make:controller NameOfResourceController -r

Route Settings:
use App\Http\Controllers\NameOfResourceController
Route::resource(‘/products’, NameOfResourceController::class)

Now look into the Resource Controller file you will find many functions ready to get started. Just you need to add your codes into appropriate functions to get started.


Create Login Page and Verification Code using Laravel Step by Step Guide

Create View with following name: login.blade.php and add following code in it.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h2>Login Form</h2>

<form action="/login" method="post">
    @csrf
  
  <div class="container">
    <label for="uname"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="uname" required>
    <br/><br/>
    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>
    <br/>    
    <button type="submit">Login</button>

</div>


  </div>
</form>

</body>
</html>

Now Let’s make Controller and then we need to add 2 functions (1 function for displaying this view and 2nd for receiving data when user submits form)

Command to Create Controller

php artisan make:controller LoginController.php

Now add following code into controller. Remember you already have a class so you just need to add 2 functions into it.

class LoginController extends Controller
{
    //
    public function index()
    {
        return view('login');
    }

    public function login(Request $req)
    {
        $uname = $req->uname;
        $pass = $req->psw;

        if($uname=="admin" && $pass=="12345")
        {
            echo "Success";
        }
        else
        {
            echo "Invalid Username or Password";
        }
    }

}

Now its time to setup Route and then run!

use App\Http\Controllers\LoginController;


Route::get('/login', [LoginController::class, 'index']);
Route::post('/login', [LoginController::class, 'login']);