簡體   English   中英

從Laravel 5.4上的數據庫中獲取對象

[英]Fetching objects from database on Laravel 5.4

我是Laravel php框架的新手。 我用這個框架做的是創建路由,控制器和模型,然后我在數據庫上創建了一些記錄(不是通過Laravel,我是直接創建數據庫)但是當我嘗試獲取它們並在其上顯示時視圖我什么也看不見,我不知道我是不是從數據庫中獲取對象,或者問題只是我沒有顯示。

這是我的路線:

Route::get('questions/show', 'questions\ShowQuestionsController@show');

控制器:

namespace App\Http\Controllers\questions;

use App\User;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class ShowQuestionsController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function show()
    {
        $questions = DB::table('questions')->get();
        return view('questions/showquestions', ['questions' => $questions]);
    }
}

風景:

showquestions!!!!!!!!!!!!111111!!!

@foreach ($questions as $question)
    <p>This is user {{ $question->statement }}</p>
@endforeach

foreach ($questions as $question) {
    echo $question->id;
}

echo $questions;

而型號:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    //
    protected $table = 'questions';
}

在日志和控制台上我沒有收到任何錯誤消息

編輯:

視圖v2:

showquestions!!!!!!!!!!!!111111!!!
<?php dd($questions); 
@foreach ($questions as $question)
    <p>This is user {{ $question->statement }}</p>
@endforeach

foreach ($questions as $question) {
    echo $question->id;
}

echo $questions;

這是我用dd($ questions)得到的:

Collection {#165 ▼
  #items: array:5 [▼
    0 => {#171 ▼
      +"id": 1
      +"statement": "Pregunta 1"
      +"num": 1
      +"created_at": null
      +"updated_at": null
    }
    1 => {#173 ▼
      +"id": 2
      +"statement": "Pregunta 2"
      +"num": 2
      +"created_at": null
      +"updated_at": null
    }
    2 => {#174 ▶}
    3 => {#175 ▶}
    4 => {#176 ▶}
  ]
}

您應確保您的視圖位於resources/views/questions目錄中,名稱為showquestions.blade.php ,它應如下所示:

showquestions!!!!!!!!!!!!111111!!!

@foreach ($questions as $question)
    <p>This is user {{ $question->statement }}</p>
@endforeach

當你有模型時,你不應該使用查詢生成器,但在控制器中你應該使用:

public function show()
{
    $questions = \App\Question::all();
    return view('questions/showquestions', ['questions' => $questions]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM