skip to Main Content

I need to use an variable to make a query in other function. How i can do this?

     public function getestados($nick)
     {
        $nivel = DB::table('locais')
        ->where('nick', $nick)
        ->get('nivel');

        return $nivel->toJson(JSON_PRETTY_PRINT);
     }

     public function elevar($nivel) {

        $novonivel = DB::table('niveis')
        ->where('cond', $nivel) // previous variable
        ->get();

        return response()->json([$novonivel]);

     }

2

Answers


  1. It looks like you use OOP so it is recommended to use the property inside the class like this

    class SomeNameHere
    {
         public $nivel; // here we declare it global on this class
    
         public function getestados($nick)
         {
            $this->nivel = DB::table('locais')
            ->where('nick', $nick)
            ->get('nivel');
    
            return $this->nivel->toJson(JSON_PRETTY_PRINT);
         }
    
         public function elevar() {
    
            $novonivel = DB::table('niveis')
            ->where('cond', this->$nivel) // previous variable
            ->get();
    
            return response()->json([$novonivel]);
    
         }
    
    }
    
    Login or Signup to reply.
  2. class Controller {
    
         protected $nivel;
    
         public function getestados($nick)
         {
            $this->nivel = DB::table('locais')
            ->where('nick', $nick)
            ->get('nivel');
    
            $this->elevar();
    
            return $this->nivel->toJson(JSON_PRETTY_PRINT);
         }
    
         public function elevar() {
    
            $novonivel = DB::table('niveis')
            ->where('cond', $this->nivel?->id) // previous variable
            ->get();
    
            return response()->json([$novonivel]);
    
         }
    }
    

    but if you call the second method separately from the first, you should store it in session()->put('key', $nivel'). and then get it in the second method session()->get('key') // $nivel

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search