将变量从一种方法传递到同一控制器中的另一种方法

时间:2019-01-10 10:55:36

标签: php laravel

我发现了类似的话题,但没有一个解决我的问题。

我在控制器中有方法,并尝试在另一个方法中但在同一控制器中使用变量。

那是我的第一种方法:

 public function show($id)
{
    $specification = RegenerationsSpecification::with('regenerations', 'user')
        ->findOrFail($id);
    return Fractal::item($specification, ['regenerations.specialist', 'regenerations.department', 'regenerations.patient', 'user']);
}

然后我尝试将$specification传递给这样的另一个函数:

    public function exportToExcel()
{
        $spec[] = $this->show($specification);
        return $spec;
}

我不知道我在做什么错,但是它没有传递$specification变量。

有人可以在这里帮助我吗? 谢谢

3 个答案:

答案 0 :(得分:0)

尝试这种方式

  public function show($id)
 {
    $specification = 
    RegenerationsSpecification::with('regenerations', 'user')
    ->findOrFail($id);
    Session::set('specification', $specification );
    return Fractal::item($specification, ['regenerations.specialist', 
    'regenerations.department', 'regenerations.patient', 'user']);
 }

 public function exportToExcel()
 {
    specification =array();
    if(Session::has('specification')) 
      $specification = Session::get('specification'); 
    }
    $spec[] = $specification;
    return $spec;
 }

答案 1 :(得分:0)

您需要使$ specification变量成为全局变量。因为您想在方法中共享该变量;

class DirectNegotiationController extends Controller
{
  protected $specification;


     public function show($id)
    {
        $this->specification = RegenerationsSpecification::with('regenerations', 'user')
            ->findOrFail($id);
        return Fractal::item($this->specification, ['regenerations.specialist', 'regenerations.department', 'regenerations.patient', 'user']);
    }

    public function exportToExcel()
    {
            $spec[] = $this->show($this->specification);
            return $spec;
    }



}

答案 2 :(得分:0)

只需执行以下操作:

//public function exportToExcel($specification)
public function exportToExcel($specification=0)
{
        $spec[] = $this->show($specification);
        return $spec;
}

第一种方法保持不变:

public function show($id)
{
    $specification = RegenerationsSpecification::with('regenerations', 'user')
        ->findOrFail($id);
    return Fractal::item($specification, ['regenerations.specialist', 'regenerations.department', 'regenerations.patient', 'user']);
}
相关问题