php - Laravel DB::select($query)

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
Answer
Solution:
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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: foreach() argument must be of type array|object, null given
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.