Take advantage of

Asked

Viewed 27 times

-1

I would like to take advantage of the result of a consultation in another function when requested

For example:

Controller

 public function funcao1(Request $request){
       $myObj = DB::select("SELECT * FROM myTable");
       return view('myView');
    }

Then I would like to use this $myObj object in another function when it came from my view, through a click or via ajax

Ajax

var form = $('<form action="{{ route('myRoute') }}"> method="post"'+
             '<input type="hidden" name="_token" value="{{ csrf_token }}"'> 
             '</form>')
$('body').append(form);
form.submit();

Controller

In that part, I would like to take advantage of the object that I set in the first function

public function funcao2(Request $request){
   echo "<pre>";
   print_r($myObj);
   echo "</pre>";
}

My route would be

Route::post('/obj', ['as' => 'myRoute', 'uses' => 'MyController@funcao2']) ;
  • 1

    Each request is unique, there is no way to reuse it this way, what you could do is cache the information for some time, but, this also has to be well thought out ...

1 answer

1

Because I’m using Laravel, I can see there’s a lot wrong with your code.

But what could be done, by responding objectively, would be to use the $this to assign the value to it.

Thus:

class MeuController extends Controller
{
    public function __construct()
    {
        $this->myObject = DB::table('...');
    }


    public function funcao1()
    {
        return view('xxx', ['myObject' => $this->myObject]);
    }

    public function funcao2()
    {
        print_r($this->myObject);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.