您可以很容易地做到这一点,只需几个步骤。
创建新的中间件(随意命名)
php artisan make:middleware UserCollectionMiddleware
创建将扩展 Eloquent 数据库集合的新集合类。此步骤不是必需的,但可以让您将来使用不同的集合类型创建不同的绑定。否则,您只能对Illuminate\Database\Eloquent\Collection 进行一次绑定。
app/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'));
}
}