Home > Enterprise >  Get player_name text value from database in jQuery
Get player_name text value from database in jQuery

Time:04-15

I want to get text value from my scores table in the database here is my score table image.

Player_name as Player_id it`s a foreign key from the players' table I can view player_id but I want to view the text value of player_id which is the player name of the players' table

Here is the image of players' table

Here is the output of what I get into my public.blade.index

This is my PublicController.php

public function view()
    {
        $data = Score::all();
        $countries = DB::table('matchhs')
            ->get();

        return view('public.index', compact('countries','data'));
    }

    public function getStates(Request $request)
    {
        $states = DB::table('scores')
            ->where('match_id', $request->match_id)
            ->get();

        if (count($states) > 0) {
            return response()->json($states);
        }
    }

This is my public.blade.php

<h1 >Select match name</h1>
            <div >
                <select  id="country">
                    <option selected disabled>Select match</option>
                    @foreach ($countries as $country)
                        <option value="{{ $country->id }}">{{ $country->match_name }}</option>
                    @endforeach
                </select>
            </div>
            <div >
                <table id="state" ></table>
            </div>

Here is my jQuery code

<script type="text/javascript">
    $(document).ready(function () {
        $('#country').on('change', function () {
            var countryId = this.value;
            $('#state').html('');
            $.ajax({
                url: '{{ route('getStates') }}?match_id=' countryId,
                type: 'get',
                success: function (res) {
                    $('#state').html('<table><thead><tr><th>SL</th><th>Player Name</th><th>Score Name</th><th>Score Slug</th></tr></thead></table>');
                    $.each(res, function (key, value) {
                        $('#state').append('<tbody><tr><td>'   value.id   '</td><td>'   value.player_id   '</td><td>'   value.score_name   '</td><td>'   value.score_slug   '</td></tr></tbody>');
                    });
                }
            });
        });
    });
</script>

CodePudding user response:

You need to do join (see Laravel docs).

public function getStates(Request $request)
{
  $states = DB::table('scores')
      ->join('players', 'scores.player_id', '=', 'players.id')
      ->where('scores.match_id', $request->match_id)
      ->select('scores.*', 'players.player_name')
      ->get();

    if (count($states) > 0) {
        return response()->json($states);
    }
}

Then player's name should be accessible in Javascript using value.player_name.

  • Related