Kusy
Kusy

Reputation: 240

pass variable from one method to another within the same controller

I found similar topic but none fixed my problem.

I have method in controller and try to use variable in another method but within same Controller.

That's my 1st method:

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

and then I try to pass $specification to another function like this:

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

I dont know what I'm doing wrong, but it doesnt pass $specification variable.

Anyone could help me here? Thank you

Upvotes: 0

Views: 107

Answers (3)

Elisha Senoo
Elisha Senoo

Reputation: 3594

Just do this:

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

First method remains unchanged:

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

Upvotes: 0

user10186369
user10186369

Reputation:

Try this way

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

Upvotes: 0

Md.Sukel Ali
Md.Sukel Ali

Reputation: 3065

You need to make $specification variable global. as You want to share this variable in your methods;

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



}

Upvotes: 0

Related Questions