PHP User
PHP User

Reputation: 2422

Laravel 5.4: attach custom service provider to a controller

I created a 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 the provider

App\Providers\AdminServiceProvider::class,

Now I try to attach it to the 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 I get this error message

Undefined variable: comments

This is the first time I try to use a custom service provider and don't know exactly how it works I'm sure there's something missing Hope you can help. Thanks in advance.

[UPDATE]

removed use App\Providers\AdminServiceProvider; from the controller

php artisan clear-compiled solved the problem but I want to attach it to some controllers not all controllers as the $comments are sent to all contollers in my app. So how to attach the service provider to specific controllers not all of them?

Upvotes: 1

Views: 1414

Answers (2)

Andriy Lozynskiy
Andriy Lozynskiy

Reputation: 2604

If you have all your admin views in one directory (views\admin for example) you can use view composer in AdminServiceProvider:

public function boot()
{
        view()->composer('admin.*', function($view){
             $view->with('comments', Orders::get_new_comments());
        });

}

It will attach comments variable to each view in your views\admin directory.

You can also attach a variable to some specific views or folders like this:

view()->composer(['admin.posts.*', 'admin.pages.index'], function($view){
      $view->with('comments', Orders::get_new_comments());
 });

Upvotes: 1

Sletheren
Sletheren

Reputation: 2486

For the undefined variable run: php artisan clear-compiled will solve it

If you want to share a variable in some of your views you can create a middleware and assign it to the views you want to share the data with:

  • First create a middleware: php artisan make:middleware someName
  • Then in the handle function you add your view sharing logic:
 $comments = Orders::get_new_comments(); 
 view()->share('comments',$comments);
 return $next($request);    
  • Then register your middleware under the $routeMiddleware array and give it an alias.

Then attach it to your routes like:

Route::group(['middleware'=> 'yourMiddlewwareName'], function(){
  //your routes
});

Upvotes: 2

Related Questions