0

My application uses Lavarel and I have certain ReactJS components. Routing is done by Laravel. For a route /Users/<userid>, if the controller is UserController.php and view is userview.blade.php, how do I get the <userid> from the URL in my react component loaded in a div on userview.blade.php?

2
  • Not sure if the same applies in React as Vue JS, but just add a window.userID JS variable on the page and have the React data model use it. Commented Dec 2, 2017 at 1:41
  • so generally speaking, server side variables and client side variables are evaluated in completely different domains. are you rendering react on the server or the client? Commented Dec 2, 2017 at 1:51

2 Answers 2

5

You can try out this library from Laracasts which allows you to pass server-side data (string/array/collection) to your JavaScript via a Facade in your Controller.

This may look something like this (haven't tested it, but you get the gist).

public function UserController($userid)
{
    JavaScript::put([
        'userid' => $userid,
    ]);

    return View::make('yourview');
}

The docs further show how to access it from your view.

https://github.com/laracasts/PHP-Vars-To-Js-Transformer

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! This still works with Laravel 8 and inside Svelte component.
0

UserController.php
you can access the userid and send it to view like this:

public function getUser($userid) {
    return view('userview')->with('userid', $userid);
}

userview.blade.php
you can grab it (in some input) like this:

<input type="text" value="{{ $userid }}" />

This is, how I understand your problem. If it is not so, kindly correct me!!!

Comments

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.