#7 What are Controllers in Laravel 5.6

Creating Controllers

The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page

Contollers reside in projectname/app/Http/ControllersDefault controller is Controller.php

Before we create a controller lets create a view file called about.blade.php inside the projectname/views directory which we want to load when the user goes to homeurl/about ( e.g. http://127.0.0.1:8000/about ) and write anything inside of it.We write contoller in PascalCase. Pascal case is a subset of Camel Case where the first letter is capitalized. That is, userAccount is a camel caseand UserAccount is a Pascal case

Now to Create a new controller create a file called PagesController inside projectname/app/Http directory and write the below code

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PagesController extends Controller {
	public function about() {
		return view( 'about' ); // This will load the 
	}
	
	# Similarty we can load mutiple pages over here by creating a function with that file name and then return view('viewfilename').
}

# Now go to projectname/routes/web.php and add the route for the view file called about.php like so:
Route::get('about', 'PagesController@about');  // Here PagesController is the name of the Controller page PagesController.php and about is the method name of the class PagesController, Hence when user goes to the homeurl/about ( e.g. http://127.0.0.1:8000/about ), it will load the about.blade.php view file from projectname/views/about.blade.php

Creating Controller using terminal

cd projectname
php artisan make:controller PostsController --resource 

# Will create a controller called PostsController.php inside the app/Http/Controllers dir and pasing the --resource flag will make sure it creates functions like index, create, store, show, edit, update and destroy automatically inside this controller file

Add your review



Leave a Reply