Laravel 5.4: attach custom service provider to a controller -
i created service provider named adminserviceprovider
namespace app\providers; use modules\orders\models\orders; use illuminate\support\serviceprovider; use view; class adminserviceprovider extends serviceprovider { public function boot() { $comments = orders::get_new_comments(); view::share('comments', $comments); } public function register() { } }
registered provider
app\providers\adminserviceprovider::class,
now try attach controller
namespace app\http\controllers\admin; use illuminate\http\request; use app\http\controllers\controller; use app\providers\adminserviceprovider; class admincontroller extends controller { public $lang; public function __construct() { } public function index(){ return view('admin/dashboard'); } }
now error message
undefined variable: comments
this first time try use custom service provider , don't know how works i'm sure there's missing hope can help. in advance.
[update]
removed use app\providers\adminserviceprovider; controller
php artisan clear-compiled solved problem want attach controllers not controllers $comments sent contollers in app. how attach service provider specific controllers not of them?
for undefined variable run: php artisan clear-compiled
solve it
if want share variable in of views can create middleware , assign views want share data with:
- first create middleware:
php artisan make:middleware somename
- then in handle function add view sharing logic:
$comments = orders::get_new_comments(); view()->share('comments',$comments); return $next($request);
- then register middleware under
$routemiddleware
array , give alias.
then attach routes like:
route::group(['middleware'=> 'yourmiddlewwarename'], function(){ //your routes });
Comments
Post a Comment