How do I access the data of some specific controllers in Laravel?

To communicate with all the views I read in the documentation, we can create

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

I found that we can also force the View Composer to communicate with only some specific views.

But how do you actually communicate with only some specific controllers?

Several controllers that we are listing have inserted some variables, object arrays, etc., ready to use.

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

Look for this in the documentation and on the internet, but can't find it, since actually only exchange data with some of the specific controllers we want?

+3


source to share


3 answers


Maybe this will help you:

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

in your desired controller



<?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);
    }

}

      

0


source


If multiple controllers need to access the same data, you may need to create a base controller that they inherit from and set that data in the controller's constructor.



Alternatively, you can save it to a session and retrieve it from there to the controllers it needs.

0


source


It might be better to use decomposition for this purpose. Write your service class for your data, bind it to a service container and then inject it into controller constructors or action methods.

0


source







All Articles