I would like to echo a table of scores within a Ajax function. Everything works (connection Ajax/Controller), but how can I create a table in my controller, that sends a whole table?
$scores = DB::table('scores')->select('teamname', 'score')->get();
Wishful outcome (It should be variables, depending on outcome of query):
response()->json(['success'=>'<table><tr><th>Teamname</th><th>Score</th></tr><tr><td>Teamname1</td><td>12</td></tr><tr><td>Teamname2</td><td>10</td></tr></table>']);
Should I make an array of $scores? Or do I need to loop to return the values? I hope you guys can help me!
2
Answers
To create html table in the controller, is not a good practice (and it is an anti-pattern too). Framework like Laravel was born precisely to separate almost three layers: the "logic", the "data" and the "views".
Html table belongs to "views" layer.
You can do that in two ways:
First way
If you call an Ajax from client, in response you can serve a json of the DATA (not HTML) of your table. And then parse this json data in your html structure in
blade
or any other html page.So, in your case, in Controller:
In your javascript get response and parse data. For example, with Axios:
then you can use the
scores
js variable in your html.Second way
You can use directly blade template, without any ajax call.
In this case:
your-page.blade.php
, something like this:You should render the view and then you can send it in the AJAX.
Please add the below line in the controller file:
After that create one file
score_table.blade.php
in your resources folder. In that file your code should be like this: