0

I have the following in my web.php. It's a route to my React application.

Route::get('/{path?}', function () {
    return view( 'welcome' );
})->where('path', '.*');

I would want of instead return view( 'welcome' ); to have

return view('welcome')->with([
    "globalData" => collect([
        'user' => Auth::user()
    ]);

And I'm having a syntax error, perhaps a typo ?

IGP
  • 14,160
  • 4
  • 26
  • 43
AlyaKra
  • 486
  • 8
  • 22

2 Answers2

1

You're not using with() correctly. If you want to pass an array like that, here's the correct syntax.

return view('welcome', ['globalData' => ['user' => Auth::user()]]);

Or

return view('welcome')->with('globalData', ['user' => Auth::user()]);

Or

$globalData = ['user' => Auth::user()];

return view('welcome', compact('globalData'));

Maybe you should also take a look at View Composers.


If you want to make use of this data only in JavaScript, you'll need to use both json_encode() to encode the array into a string and JSON.parse() to convert this json string into a proper JS object.

var globalData = JSON.parse({{ json_encode($globalData) }}); // try with {!! !!} if it doesn't work. 
IGP
  • 14,160
  • 4
  • 26
  • 43
  • Correct ! Thank you very much. I know I'm bit off topic but I have in my blade `` and receiving the following error `Call to a member function toJson() on array` . If you have any idea I will appreciate it. – AlyaKra May 09 '21 at 08:01
  • `toJson()` is a `Model` method. `$globalData` is a plain array. I'll add something in the answer. – IGP May 09 '21 at 08:06
  • Thank you. Here is what I'm following so you can get an idea. I think he got some code wrong. – AlyaKra May 09 '21 at 08:08
  • https://stackoverflow.com/questions/55565500/how-do-i-check-if-user-is-logged-in-in-a-react-component-when-using-laravel-au – AlyaKra May 09 '21 at 08:11
  • Thank you very very much. `{{ $globalData }}` is to display the value in the blade right ? – AlyaKra May 09 '21 at 08:13
  • Yes. `{{ }}` echo whatever is inside. – IGP May 09 '21 at 08:15
  • It gives me this `.htmlspecialchars() expects parameter 1 to be string`. – AlyaKra May 09 '21 at 08:16
  • That answer you linked has the same typo ADyson pointed out in the comments. `toJson()` works if it's a Collection too but it's a bit unnecessary. – IGP May 09 '21 at 08:16
  • It was because I was outputin an array inside {{}} – AlyaKra May 09 '21 at 08:40
1
return view('welcome')->with('globalData', ['user' => Auth::user()]);

this is the syntext to use when you are using with for passing data.

see the example here : How to pass data to view in Laravel?