从MySQL获取Laravel错误:尝试获取非对象

时间:2017-08-10 12:20:31

标签: php mysql laravel

我是Laravel的新手,我想创建一个使用MySQL获取产品的小型localhost网站。

在我研究并应用了一些答案后,我仍有问题:

尝试获取非对象的属性(查看: F:\ XAMPP \ htdocs中\ Laravel \资源\视图\ welcome.blade.php)

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    //return view('welcome');
    $products = DB::table('laravel_products')->pluck('product_name', 'product_about', 'producer_ID', 'product_added');
    return view('welcome', ['products' => $products]);
});

welcome.blade.php

<table class="table table-striped">
                        <thead>
                            <tr>
                                <td>Product name</td>
                                <td>Description</td>
                                <td>Date added</td>
                            </tr>
                        </thead>
                        <tbody>
                        <?php

                        foreach ($products as $value) {
                            echo '
                                <tr>
                                    <td>' . $value->product_name . '</td>
                                    <td></td>
                                    <td></td>
                                </tr>
                            ';
                        }

                        ?>
                        </tbody>
                    </table>

我该怎么做才能从MySQL中获取?

1 个答案:

答案 0 :(得分:1)

你应该试试这个:

Route::get('/', function () {
    //return view('welcome');
    $products = DB::table('laravel_products')->select('product_name', 'product_about', 'producer_ID', 'product_added')->get();
    return view('welcome', compact('products'));
});


<table class="table table-striped">
                            <thead>
                                <tr>
                                    <td>Product name</td>
                                    <td>Description</td>
                                    <td>Date added</td>
                                </tr>
                            </thead>
                            <tbody>
                         @if(isset($products))
                            @foreach($products as $value)

                                    <tr>
                                        <td> {{$value->product_name}}</td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                            @endforeach
                            @endif
                            </tbody>
                        </table>

希望这对你有用!!!