In Laravel controller is most important part to create the connection between our business logic to our view. we will learn create controller in laravel 8.Laravel is a MVC pattern and C stands for controller.
It’s responsible for to receive the input from user, process them and validate the input then it send to model and business logic of our application.
Default directory for controllers in Laravel 8 is app\Http\Controllers
.
Let’s create a controller in Laravel 8
Create controller in laravel 8
There is 2 ways to create the controller
- Using Artisan command
- Creating controller manually in directory
Below is the command to create the controller using artisan
php artisan make:controller TestController
Also we can create manually in file system below file /app/Http/Controllers/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
function index(){
return "Hello";
}
}
In the same way you can create a controller in subfolder
Create a controller in subfolder
php artisan make:controller Api/TestController
It will create the controller in app/Http/Controllers/Api/TestController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TestController extends Controller
{
//
}
Define the route for controller
We have successfully created our controller but route is not created yet for accessing for controller from URL, So create a route in route/web.php
<?php
use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\TestController;
Route::get('/test',[TestController::class, 'index']);
Here, we imported TestController and then used in our get route. Whenever a request exact match with /test
it will call the TestController index method with specified params.
Parametrized Route for controller
In above example we called a simple route to serve the request, now we will create a route with param
<?php
use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\TestController;
Route::get('/test/{id}',[TestController::class, 'index']);
Here, we used {id}
as paramo so our controller method will accept a param
function index($id){
return "Hello world $id";
}
Creating Controller Middleware
In our last article Laravel middleware we demonstrate how to create and use middleware, now we can also use the middleware in controller.
There is 2 ways to use middleware in controller.
- In Route
- In Same Controller
Route Middleware
Route::get('/test', [TestController::class, 'index'])->middleware('auth');
In controller middleware we can define in same controller using $this->middleware
in constructor
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
}
function index(){
}
}
I hope you find it well…