Laravel not getting info out of database, displays erros

80 Views Asked by At

Sorry, I'm new to developing on Laravel. I'm trying to show info contained in the database on my page. But it can't find the variable holding all the data. I can see the info in Tinker, but i can't seem to deplay is.

I posted some pictures so you can have a look. I'd love to hear your feedback.

Images: https://i.stack.imgur.com/ynfkP.jpg

Code:

Route:

<?php

Route::get('/', function () {
    return view('index');
});

Route::resource('complaints', 'ComplaintController');

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Complaint;

class ComplaintController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $complaints = Complaint::all();

        return view('index', compact('complaints'));
    }

Blade:

@extends('layout')

@section('title','Welcome')

@section('content')

{{-- @foreach ($complaints as $complaint)
    <h1>{{ $complaint->title }}</h1>
    <p>{{ $complaint->body }}</p>
@endforeach --}}

{{ $complaints }}


@endsection
4

There are 4 best solutions below

0
On BEST ANSWER

You are not routing to the correct function in your controller. Try this

Route::resource('complaints', 'ComplaintController@index');
0
On

Try it with another syntax like below:

public function index() {
    $complaints = Complaint::all();
    return view('index')->with(compact('complaints'));
}

or

 public function index() {
    $complaints = Complaint::all();
    return view('index')->with('complaints', $complaints);
}
1
On

As @amirhosseindz said
When you're visiting this url : http://127.0.0.1:8000/complaints it will work because you're hitting

Route::resource('complaints', 'ComplaintController');

But when you visit this url : http://127.0.0.1:8000

you're hitting this action:

Route::get('/', function () {
    return view('index');
});

where $complaints doesn't exists

0
On

You should try this:

Your Controller

public function index() {
    $complaints = Complaint::all();
    return view('index',compact('complaints'));
}

Your View (index.blade.php)

@extends('layout')

@section('title','Welcome')

@section('content')

  @if(isset($complaints))
   @foreach ($complaints as $complaint)
    <h1>{{ $complaint->title }}</h1>
    <p>{{ $complaint->body }}</p>
   @endforeach
  @endif


@endsection