Laravel Controllers


Laravel Controllers – The Laravel Controllers is used to defined group related request handling logic into a single class and stored in the app/Http/Controllers directory.


Laravel Controllers.

Let us understand how to use laravel Controllers.

Function:-

There are some followings function available in laravel Controllers.

  • 1. Introduction.
  • 2. Basic Controllers.
  • 3. Controller Middleware.
  • 4. Resource Controllers.
  • 5. Dependency Injection & Controllers.

1. Introduction.

Insead of defining all of your request handling logic closures in route file, you may wish to organize this behavior using controller classes. Controller can group related requst handling logic into a single class. Controller are stored in the app/Http/controllers directory.

2. Basic Controllers.

Defining Controllers

In MVC framework, the letter ‘C’ stands for controller. It acts as a directing traffic between Views and Model. The controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller action.

EXAMPLE

First we have to create UserController using command prompt.

php artisan make:controller UserController --plain
Laravel Controllers

Controller Path:-

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function parameter($id)
	{
		return 'Parameter_id_'.$id;
	}
}

Define a route to this controller like this:-

Route::get('/parameter/{id}', 'UserController@parameter');
Laravel Controllers

Controllers & Namespaces

We don't need to define full controller namespace when we are defining the controller route. We only defined the specify part of the class name which is comes after the App/Http/controllers part of the namespace.

Route::get('foo', 'Photos\AdminController@method');

Single Action Controller

We want to define a controller that handles a single action, then we can use _invoke
method on the controller.

Let's look at a simple example.

<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;

class Showprofile extends Controller
{
    public function __invoke($id)
    {
        return "Welcome To Tutorialsplane.com";
    }
}

When you use route for single action controller, then do not need to define method.

Route Path:-

Route::get('user/{id}', 'ShowProfile');
Laravel Controllers

3. Controller Middleware.

We can also assign the middleware to the controller route in your route file.

Route::get('profile', 'UserController@show')->middleware('auth');

By using middleware method to your controller constructor we can easily define middleware to the controller action.

Let's look at a simple example.

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
    }
}

4. Resource Controllers.

This routing is used to assign CRUD route to the controller with single line code. Like , you want to create a controller that handle all Http request for photo stored using make:controller Artsian command.

php artisan make:controller PhotoController --resource

Then it will generate controller at app/Http/controller/PhotoController.php.

Route::resource('photos', 'PhotoController');

This route declaration creates multiple route to handle a lot of action on resource.

Laravel Controllers

Spoofing Form Methods

Html form can not create PUT, PATCH or DELETE request. You need to add a hidden _method field to spoof these Http verbs. Method field helper can create this field for you.

{{ method_field('PUT') }}

Partial Resource Routes

In this we can specify the subset of action. the controller should handle the default action.

Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);
Route::resource('photo', 'PhotoController', ['except' => [
    'create', 'store', 'update', 'destroy'
]]);

Naming Resource Routes

All controller have a route name, yet we can override these name by passing names array.

Route::resource('photo', 'PhotoController', ['names' => [
    'create' => 'photo.build'
]]);

Naming Resource Route Parameters

The Route::resource is generate the route parameter for resource route based on single version of resouce name. We can easily override by passing parameter in array.
The array should be an associative array of resource name and parameter names.

Route::resource('user', 'AdminUserController', ['parameters' => [
    'user' => 'admin_user'
]]);

Localizing Resource URIs

This method is used to create and edit action verbs. You can use Route::resourceVerbs methods. It will be generate in boot method of your AppServiceProvider.

Let's look at a simple example.

use Illuminate\Support\Facades\Route;
public function boot()
{
    Route::resourceVerbs([
        'create' => 'crear',
        'edit' => 'editar',
    ]);
}

Route path:-

Route::resource('fotos', 'PhotoController')

Supplementing Resource Controllers

If you want to add some additional route to resource controller. Tou should define before you call route::resource.

Route::get('photos/popular', 'PhotoController@method');

Route::resource('photos', 'PhotoController');

5. Dependency Injection & Controllers.

Constructor injection

The Laravel Service Container is used to resolve the controllers. You are able to type hint any dependencies your controller which need in its constructor. The dependencies will automatically be resolved and injected into the controller.

Contoller Path:-

Let's look at a simple example.

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

class ImplicitController extends Controller {
   private $myclass;
   
   public function __construct(\MyClass $myclass){
      $this->myclass = $myclass;
   }
   public function index(){
      dd($this->myclass);
   }
}

Route Path:-

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Method Injection

In this method, you can also type-hint dependencies on your controller's action methods.

Controller Path:-

Let's look at a simple example.

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

class ImplicitController extends Controller {
   public function index(\MyClass $myclass){
      dd($myclass);
   }
} 

Route path:-

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Advertisements

Add Comment

📖 Read More