Search code examples
laravel-5.7

Pulling Single Quote From DB and displaying on page using Laravel


I have some quotes in a database and am trying to use Laravel to display it on a page. I have the quotes being pulled from the controller then passed to the view but I am getting an error:

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>

Migration Table for Quotes

<?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');
    }
}

Why do I get this error? And how do I get only one quote to display at a time and only change upon each page refresh?

Thank you.


Solution

  • I advise you to input the variable $quotes in the controller, And I remember the passed variable array key which can use and not have to use all function.

    The below code from laravel manual:

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

    change

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

    into

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