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 ?

2
  • You're missing another ]) as far as I can see Commented May 9, 2021 at 7:53
  • @ADyson I thought so, but I have this error syntax error, unexpected '}', expecting ';' Commented May 9, 2021 at 7:55

2 Answers 2

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. 
Sign up to request clarification or add additional context in comments.

9 Comments

Correct ! Thank you very much. I know I'm bit off topic but I have in my blade <script> let globalData = "{!! $globalData->toJson() !!}"; </script> and receiving the following error Call to a member function toJson() on array . If you have any idea I will appreciate it.
toJson() is a Model method. $globalData is a plain array. I'll add something in the answer.
Thank you. Here is what I'm following so you can get an idea. I think he got some code wrong.
Thank you very very much. {{ $globalData }} is to display the value in the blade right ?
|
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?

1 Comment

Yes I missed with-> as IGP said. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.