2017-08-10 158 views
1

我是Laravel的新手,我想製作一個使用MySQL獲取產品的小本地主機網站。Laravel從MySQL獲取錯誤:試圖獲取非對象的屬性

我研究並應用了一些答案後,我仍然有問題:

試圖讓非對象(查看物業: 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

'$ value ['product_name']'pluck會返回一個數組而不是集合對象 – linktoahref

+0

我試過了,結果是:Illegal string offset'product_name'(View:F:\ xampp \ htdocs \ Laravel \ resources \ views \ welcome.blade.php) –

回答

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> 

希望這對你的工作!

+0

我認爲你很接近,但仍然說:使用未定義的恆定產品 - 假定'產品' –

+0

@PanameraTurboS等待檢查它 –

+0

它的工作原理是缺少「$」:路線:: 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)); }); 但不顯示任何產品 –

相關問題