仅使用Laravel查询生成器将所选字段显示到视图

时间:2019-05-22 01:15:26

标签: laravel eloquent laravel-blade

每次刷新页面时,我每次都会在屏幕上显示一个报价。数据库显示数据正常;问题是,当我只需要引用和作者姓名时,我也会在屏幕上显示(id)。如何在我的视图中“排除” ID字段?

控制器

public function index()
{
    $quotes = DB::table('quotes')->inRandomOrder()->first();

    return view('home', compact('quotes'));
}

刀片/视图

@foreach($quotes as $quote)
    <p>{{$quote}}</p>
@endforeach

1 个答案:

答案 0 :(得分:4)

根据@devk的评论

编辑

  

通常回答OP的问题,但是这里的代码(以及OP帖子中的代码)   完全没有道理。 -> first()将返回null或单个   引号,但@foreach(..)的使用就像是引号的集合

您可以像这样进行查询:

include("GlobalVariables.php");

$conn=mysqli_connect('this info is correct');
$email=$_POST["EMAIL"];
$username=$_POST["USERNAME"];
$password=$_POST["PASSWORD"];
$ip=$_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d');

if (check_username_valid($conn,$username)==false){
    $check1 = inject_sql($conn,"SELECT * FROM `userdata` WHERE `ip` = '$ip'");
    $check2 = inject_sql($conn,"SELECT * FROM `userdata` WHERE `username`='$username'");
    if (mysqli_row_count($check)==$max_accounts&&$check2["username"]==null){
        inject_sql($conn,"INSERT INTO `userdata`(`ip`, `username`, `password`, `email`, `reg_date`, `verified`) VALUES ('$ip','$username','$password','$email','$date',false");
        echo "0";
        $check3 = inject_sql($conn,"SELECT * FROM `userdata` WHERE `reg_date` = '$date' AND `username` = '$username");
        echo "1";
        if ($check3["username"] == "$username"){
            echo "2";
            header('Location:../index.html');
        }
    }
    else{
        header('Location:../index.html');
    }
}
else{

}

用表中的字段名称替换“ quote”和“ author”。
并返回报价:

$quote = DB::table('quotes')->select('quote', 'author')->inRandomOrder()->first();

然后在刀片中显示对象:

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

或显示字段:

<p>{{$quote}}</p>

如果要显示多个引号,请对所有引号进行如下查询:

@if(!$quote->isEmpty())
    <p>{{$quote->quote}}</p>
    <small>{{$quote->author}}</small>
@endif

在刀片中,您可以遍历集合:

$quotes = DB::table('quotes')->select('quote', 'author')->inRandomOrder()->get();

@foreach($quotes as $quote)
    <p>{{$quote}}</p>
@endforeach