How to add an object to Laravel IOC Container from middleware

I want to create an object in my middleware (in this case, a compilation from an Eloquent request), and then add it to the IOC container so that I can type signature types in my controllers to access it.

Is it possible? I can not find examples on the Internet.

+4
source share
1 answer

You can do this very simply in a few steps.

Create a new middleware (name it whatever you want)

php artisan make:middleware UserCollectionMiddleware

, Eloquent. , , . Illuminate\Database\Eloquent\Collection.

//UserCollection.php

<?php namespace App\Collection;

use Illuminate\Database\Eloquent\Collection;

class UserCollection extends Collection {

}

app/Http/Middleware/UserCollectionMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;
use App\User;
use App\Collection\UserCollection;

class UserCollectionMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app()->bind('App\Collection\UserCollection', function() {
            // Our controllers will expect instance of UserCollection
            // so just retrieve the records from database and pass them
            // to new UserCollection object, which simply extends the Collection
            return new UserCollection(User::all()->toArray());
        });

        return $next($request);
    }

}

,

Route::get('home', [
    'middleware' => 'App\Http\Middleware\UserCollectionMiddleware',
    'uses' => 'HomeController@index'
]);

,

<?php namespace App\Http\Controllers;

use App\Collection\UserCollection;

class HomeController extends Controller {

    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index(UserCollection $users)
    {
        return view('home', compact('users'));
    }

}
+4

All Articles