Victordb
Victordb

Reputation: 549

Laravel pass controller database query to view

I'm trying to display a query in a view. Each result I want to be a submit button that would submit his value when clicked.

In ListController I have this code:

 public function index()
    {
        $tables = DB::table('tables')->select('name')->get();

        return view('welcome', compact('tables'));
    }

In welcome.blade.php I have:

            <form action="{{ route('get_table') }}" method="POST">
                {{ csrf_field() }}

                @foreach($tables as  $data)
                <input type="submit" name="tables[]" value="{{ $data }}">
                @endforeach
            </form>

In routes web.php I have:

Route::get('/', 'ListController@index');

And I get this error:

"htmlspecialchars() expects parameter 1 to be string, object given (View:...welcome.blade.php)"

What am I doing wrong?

Upvotes: 1

Views: 1553

Answers (1)

aynber
aynber

Reputation: 23011

$data is an object, despite you only selecting one column. You have two options:

Use the name property for $data:

<input type="submit" name="tables[]" value="{{ $data->name }}">

Or use pluck to retrieve a collection of single names.

$tables = DB::table('tables')->pluck('name');

Upvotes: 1

Related Questions