从数据库中获取数据并显示到 Laravel 中的刀片模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37316393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:50:05  来源:igfitidea点击:

Get data from database and display to blade template in laravel

phplaravel

提问by Mr D

I have a problem when I learning laravel. My views include master.blade.phpand top.blade.phpfile. In master.blade.php, I used @include('top')command to get content show UI. But now I don't know how to get and passing database to top.blade.php. I was used direct App\Article;to do this. can anyone help me? thanks.

我在学习 Laravel 时遇到了问题。我的意见包括master.blade.phptop.blade.php文件。在 中master.blade.php,我使用@include('top')命令来获取内容显示 UI。但现在我不知道如何获取数据库并将其传递给top.blade.php. 我是直接App\Article;用来做这个的。谁能帮我?谢谢。

Master.blade.php file

Master.blade.php 文件

@include('top')

Top.blade.php file

top.blade.php 文件

<?php 
use App\Article;
$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
 ?>
@foreach ($articles as $a)
{{ $a->title }}
@endforeach

采纳答案by Alexey Mezenin

You could do this:

你可以这样做:

<?php 
$articles = \App\Article::orderBy(DB::raw('RAND()'))->take(1)->get();
?>

But it's better to keep data logic in a model or a controller and pass it to the views.

但是最好将数据逻辑保留在模型或控制器中并将其传递给视图。

回答by Thibault Dumas

Juste use a Controller to pass database data in to your view, it should be

Juste 使用控制器将数据库数据传递到您的视图中,它应该是

ArticlesController.php

文章控制器.php

$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
return view('master', compact('articles');

It's just an example, but now top.blade.php which is included in master, will contain $articles.

这只是一个例子,但现在包含在 master 中的 top.blade.php 将包含 $articles。