0

I have JS code:

var pobTeamId = document.getElementById('team_a_id').value;
var query = "<?php echo Sport::find(Team::find(pobTeamId)->sport_id)->id; ?>";

I need insert value pobTeamId in variable query.

I don't know how I can add this variable. I trying using this:

  • ...Team::find(pobTeamId)...

  • ...Team::find($pobTeamId)...

  • ...Team::find(?>"pobTeamId"<?php)...

    but Laravel returned only errors.

1
  • You can't. You're going the wrong direction. PHP (processed on the server) can output javascript. Javascript (processed on the client generally) can't output PHP (at least not how you're trying to do it) You can send and receive information from PHP through ajax calls. Commented Mar 28, 2017 at 17:49

2 Answers 2

1

You approach is wrong! PHP won't be able to get the value of pobTeamId.

Use ajax to send the value to the Controller

var pobTeamId = document.getElementById('team_a_id').value;

// Initiate an Ajax either on page load or on button click
$.ajax({
    url: '', // path you defined in your routes file
    type: '' // either POST or GET
    data: {
         "pobTeamId": pobTeamId
    },
    success: function (data) {
    }
});

and in the Controller you would have access to the pobTeamId

public function yourFunction(Request $request)
{ 
    $pobTeamId = $request->input('pobTeamId');

    $sport_id = Sport::find(Team::find($pobTeamId)->sport_id)->id;        
}

you would need to reference the Sport Model in your controller and add an appropriate route

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

Comments

1

Do it like this:

<form method="get" action="{{ route('get_sport_id') }}">
    <input id="team_a_id" value="" name="team_a_id"/>
    <button type="submit"> Fetch </button>
</form>

Then in your controller:

public function getSportID()
{
    $sport_id = Sport::find(Team::find(request()->get('team_a_id')->sport_id)->id;

    return back()->with('sport_id', $sport_id);
}

With a corresponding route that's something like this:

Route::get('/sport-id', 'SportController@getSportID')->name('get_sport_id');

Now your view will have access to $sport_id. Of course, you should check isset($sport_id) before attempting to use it in the view.

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.