Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a Laravel project that does custom SQL commands from input. I have the following functions.

Route

 Route::patch('/form-submit', function(Request $request){
  $query = $request->input('query');
  return view('welcome', compact('query'));
});

Welcome.blade.php

<form method="POST" enctype="multipart/form-data" action="/form-submit" class="text-end">
   {{ method_field('PATCH') }}
   @csrf
   <input name="query" value="{{ $query }}" id="input" class="form-control w-20">
   <button type="submit" id="button" class="btn btn-sm btn-info mt-3">Submit</button>
 </form>

<?php
  $querys = DB::select($query);
?>

Now I want to loop through all the values that the SQL command gives me. For example, for the input "SELECT * from users" I will get all the users and I can show their name using:

@foreach($querys as $data)

  {{$data->name}}

@endforeach

But I would like to show all the data for the user, including name, sex, id, age, etc. I tried multiple options but I didn't find yet a solution. The query will always be different so I will not know what data do I have to show. For example, if I type "SELECT * from notifications" I want to add all the informations from the database in a table.

Can anyone help me?

Thank you

question from:https://stackoverflow.com/questions/65943379/laravel-dbselectquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can return array from Model use ->toArray() method and then you will have associative array. You can do something like that

@foreach($querys as $field=>$value)

<p> {{$field}} = {{$value}} </p>

@endforeach

Where $field it's field name in table and $value it's column value. Also you need check nesting, if you have several results


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...