首页 文章

如何从主视图Laravel 5.7返回表数据

提问于
浏览
-2

我确定这是一个新手问题,但现在让我烦恼了一段时间 .

我有一张推荐表,我正在尝试在主页上输出一些推荐信 .

这就是我的目标 .

Route:(web.php)

Route::get('/', function () {
    return view('home');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');

Home Controller:

use DB;
use App\Testimonial;
...
public function index()
{
    $testimonial = DB::table('testimonials')->orderBy('id', 'DESC')->get();
    return view('home', compact('testimonials'));
}

Home View / Blade:

@foreach ($testimonial as $test)
<h4>{{$test->first_name}}</h4>
<p>{{$test->testimonial}}</p>
@endforeach

Error:

未定义的变量:见证

对此问题的任何见解都会有所帮助 .

3 回答

  • 2

    “/”的路径直接进入“主页”视图,而不通过控制器 . 更改该路由以转到相同的控制器方法将修复它 .

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

    变量名也需要在控制器和视图中匹配 .

    Controller

    use DB;
    use App\Testimonial;
    ...
    public function index()
    {
        $testimonials = DB::table('testimonials')->orderBy('id', 'DESC')->get();
        return view('home', compact('testimonials'));
    }
    

    View

    @foreach ($testimonials as $test)
        <h4>{{$test->first_name}}</h4>
        <p>{{$test->testimonial}}</p>
    @endforeach
    

    这应该有效,假设您的数据库查询实际上返回结果 . 如果它仍然无效,请在分配后检查$ testimonials变量中的内容 .

    dd($testimonials);
    
  • 1

    你正在返回错误的变量,改变你的回报:

    return view('home', compact('testimonial'));
    

    一切都很好 .

  • 0

    由于您的变量名为 $testimonial ,因此您应该传递:

    // singular testimonial
    return view('home', compact('testimonial'));
    

    然后,您可以使用:

    @foreach ($testimonial as $test)
    

相关问题