Search code examples
phparrayslaravelcontrollertraits

How to access array data declared in one controller in another controller?


I have an array with some data in a controller, something like this:

$data['countries'] = array(
    ["code" => "fr","title" => "French", "flag" => "https://www.makkumbeach.nl/img/flag_fe.gif"], 
    ["code" => "es","title" => "Spain", "flag" => "https://www.eurojobs.com/templates/Eurojobs/main/images/flags/Spain.gif"]
);

The problem is that I need this array inside another controller. Is there a simple solution for that? Instead of copying the data twice.


Solution

  • Use traits.

    <?php
    
    namespace App\Http\Controllers\Traits;
    
    use App\Services\ArticleService;
    
    trait CountriesDataTrait
    {
        public function addCountriesData(&$data = [])
        {
            $data['countries'] = array(
                ["code" => "fr","title" => "French", "flag" => "https://www.makkumbeach.nl/img/flag_fe.gif"],
                ["code" => "es","title" => "Spain", "flag" => "https://www.eurojobs.com/templates/Eurojobs/main/images/flags/Spain.gif"]
            );
            return $data;
        }
    }
    

    Use Trait in Controllers

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Routing\Controller;
    use App\Http\Controllers\CountriesDataTrait;
    
    class FirstController extends Controller
    {
        use CountriesDataTrait;
    
        public function method()
        {
            $data = [
                // some data
            ];
            $data = $this->addCountriesData($data);
            // your logic 
        }
    }
    

    Use same trait secondController

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Routing\Controller;
    use App\Http\Controllers\CountriesDataTrait;
    
    class SecondController extends Controller
    {
        use CountriesDataTrait;
    
        public function method()
        {
            $data = $this->addCountriesData();
            // your logic 
        }
    }