从数据库中提取单引号并使用 Laravel 在页面上显示

Pulling Single Quote From DB and displaying on page using Laravel

我在数据库中有一些引号,我正在尝试使用 Laravel 将其显示在页面上。我从控制器中提取引号然后传递给视图,但出现错误:

Undefined variable: quotes (View: C:\laragon\www\resources\views\inc\quote.blade.php) (View: C:\laragon\www\resources\views\inc\quote.blade.php) (View: C:\laragon\www\resources\views\inc\quote.blade.php

QuotesController.php

namespace App\Http\Controllers;

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

class QuotesController extends Controller
{
    public function index()
    {
        $quotes = DB::table('quotes')->get();

        return view('inc.quote', ['quotes' => $quotes]);
    }
}

quote.blade.php

<div id="MarketingQuote" class="container-fluid padding bg-light">
    <div class="row">
        <div class="col-lg-6">
            <h2>Marketing Quote of the day</h2>

            @foreach($quotes->all() as $quote)
                <li>{{$quote}}</li>
            @endforeach

            <br>
        </div>
        <div class="col-lg-6">
            <img src="img/computer.jpg" class="image-fluid" alt="">
        </div>
    </div>
</div>

引用迁移Table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateQuotesTable extends Migration
{

    public function up()
    {
        Schema::create('quotes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('quote');
            $table->string('author');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('quotes');
    }
}

为什么会出现此错误?我如何才能一次只显示一个报价并且只在每次页面刷新时更改?

谢谢。

我建议你在controller中输入变量$quotes,而且我记得传递的变量数组键可以使用,不必使用所有功能。

以下代码来自 laravel 手册:

Route::get('greeting', function () {
        return view('welcome', ['name' => 'Samantha']);
    });
    Hello, {{ $name }}.

改变

@foreach($quotes->all() as $quote)
                <li>{{$quote}}</li>
@endforeach

进入

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