从Laravel 5.4上的数据库中获取对象

时间:2017-02-18 17:20:28

标签: php database laravel 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 ▶}
  ]
}

1 个答案:

答案 0 :(得分:0)

您应该确保您的视图位于名称为resources/views/questions的{​​{1}}目录中,它应如下所示:

showquestions.blade.php

当你有模型时,你不应该使用查询生成器,但在控制器中你应该使用:

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

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