#4 Controllers in Laravel

#4 Controllers in Laravel

Why Laravel Controllers

Controller is one of the major part of MVC (Model-View-Controller) architecture. In our previous lecture, we've learned about laravel routing, now it might be not good to write all the business logic in a one file in route - web.php.

To write logic what a route will do, we'll write that in controller. We'll understand the concept of Laravel Controllers now. Default Controller location of Laravel is 



Basic Controller Example in Laravel

 Here is a basic controller example in Laravel with Laravel Route -

use App\Http\Controllers\PostsController;
Route::get('posts', [PostsController::class, 'index'])->name('posts.index');


So, in the PostsController, we've to make a function called index, and the format would be like this in Laravel Controller.


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Post;

class PostsController extends Controller
     * Show All Post Resource
     * @return View
    public function index()
        $posts = Post::all();
        return view('posts.index', compact('posts'));


So, In controller here is some key points -

  1. Laravel Controller Extend or inherit the Laravel's Base/Parent Controller class. 
  2. We've to import models or other classes at top, like use App\Models\Post for Post Model's import system.
  3. We've to define a public function functionName(){ // } to make a function that is visible to all.
  4. Inside function, we can fetch data like $posts = Post::all() to find all posts
  5. We then finally return a view and pass that data to the view. Like, in the above example - We've created posts variable and we pass this data to the posts.index view. This view file is inside the posts/index.blade.php
  6. To pass data to the view, we could use compact() function, or just array [].



Pass Parameter in URL and Pass to Controller Laravel

 Assume, we want to create an url like this with post slug, http://test.com/posts/test-post

Where test-post is the post's slug. So, our Route and Controller code would be - 

use App\Http\Controllers\PostsController;
Route::get('posts/{slug}', [PostsController::class, 'show'])->name('posts.show');




Official Documentation of Laravel - https://laravel.com/docs/7.x/controllers

Laravel 8 Contrller's documentation - https://laravel.com/docs/8.x/controllers


#3 Basic about Laravel Routing
#5 Laravel Views