Search code examples
angularjslaravellaravel-views

Javascript::put() or return view('index', compact($data))


Please look into my controller

    class myController extends Controller
    {
      $markets = Market::all();
      \JavaScript::put([
         'markets' => $markets,
      ]);

      return view('test.index');
    }

Using this method, I can get all markets in my angularjs file in markets variable.

I saw something like below

    class myController extends Controller
    {
      $markets = Market::all();
      return view('test.index', compact($markets));
    }

which one would I prefer? what is the advantages of both? what is the difference of both?


Solution

  • 1st Method: It is useful if you want to define your javascript variable from laravel controller method. Then you can use your variable directly into javascript.

    console.log(markets);
    

    But problem is you can't call a PHP or laravel function on that variable.

    2nd Method: It's just regular PHP variable declaration and pass the variable to blade template. You can call any php or laravel function on it. But it is not available in javascript. If you want to make it available.

    var markets = "{{ $markets }}";
    console.log(markets);
    

    Both have their pros and cons.