1

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.

2
  • You mean send this array to another controller?? Commented Jun 10, 2018 at 13:53
  • It totally depends on your class structure and dataflow. How are the two controllers connected? Where does the controller get the data from? And are the two controllers included by the same master object? Is there a data-connection between them? What does your system architecture look like? Commented Jun 10, 2018 at 13:55

1 Answer 1

1

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 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.