如何访问Laravel中某些特定控制器的数据?

For sharing data with all views I read in documentation we can create

View::share('key', 'value');

I found that also we can make View Composer to share data with only some specific views.

But how to actually share data with only some specific controllers?

Few controllers we list to have injected some variables, objects arrays etc ready to use.

One Idea that comes to my mind is to create for them middleware... But I don't think it should be done something this way

Looking for this in documentation and web but cannot found, so how actually share data only with some specific controllers that we want to?

Maybe this will help for you:

Some snippets from conetix.com.au/blog/simple-guide-using-traits-laravel-5 You can use use ExampleCode; in the controller you wish

<?php 
namespace App\Traits;

trait ExampleCode
{
    public function asd()
    {
        return [1,2,3];
    }
}

namespace App\Something;

use App\Traits\ExampleCode;

class Someclass
{
    use ExampleCode;

    public $yourarray;

    public function __construct()
    {
        $this->yourarray = $this->asd();
    }

    public function hi(){
         dd($this->yourarray);
    }

}

If multiple controllers need to have access to the same data, then you may want to consider creating a base controller that they inherit from and setting that data in the constructor of the controller.

Alternatively you can store it in the session and retrieve it from there in the controllers that need it.

Maybe it's better to use decomposition for this purpose. Write some service class for your data, bind it to your service container and then inject it into controllers constructor or action methods.