Reputation: 7990
I want to create an object in my middleware (in this case, a collection from an Eloquent query), and then add it to the IOC container so I can type-hint method signatures in my controllers to access it.
Is this possible? I can't find any examples online.
Upvotes: 4
Views: 2531
Reputation: 9520
You can do that very easy, in several steps.
Create new middleware (name it like you want)
php artisan make:middleware UserCollectionMiddleware
Create new collection class that will extend Eloquent database collection. This step is not required, but will let you in future to create different bindings, using different collection types. Otherwise you can do only one binding to Illuminate\Database\Eloquent\Collection
.
app/Collection/UserCollection.php
<?php namespace App\Collection;
use Illuminate\Database\Eloquent\Collection;
class UserCollection extends Collection {
}
Add your bindings in 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);
}
}
Don't forget to put the middleware on the desired routes, otherwise you will get an error
Route::get('home', [
'middleware' => 'App\Http\Middleware\UserCollectionMiddleware',
'uses' => 'HomeController@index'
]);
Now you can type hint this dependency in your controller like this
<?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'));
}
}
Upvotes: 6