Laravel访问数据阵列

时间:2018-06-10 13:51:21

标签: php laravel laravel-5

我在控制器中有一些包含一些数据的数组,就像这样..



        $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"]
        );




但问题是我在另一个控制器中需要这个数组,有一个简单的解决方案吗?而不是两次复制数据。

1 个答案:

答案 0 :(得分:1)

使用特征。

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

在控制器中使用Trait

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

使用相同的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 
    }
}