【问题标题】:Laravel not getting info out of database, displays errosLaravel 没有从数据库中获取信息,显示错误
【发布时间】:2019-04-15 01:49:08
【问题描述】:

抱歉,我是 Laravel 开发新手。我正在尝试在我的页面上显示数据库中包含的信息。但它找不到保存所有数据的变量。我可以在 Tinker 中看到信息,但我似乎无法播放。

我贴了一些图片,你可以看看。我很想听听您的反馈。

图片:https://imgur.com/a/zLSqSDG

代码:

路线:

<?php

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

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

控制器:

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

刀片:

@extends('layout')

@section('title','Welcome')

@section('content')

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

{{ $complaints }}


@endsection

【问题讨论】:

  • 如果您将代码发布为文本而不是图像,会更容易提供帮助。
  • 这里也添加代码,包含路由、控制器和刀片文件。
  • 你的代码没问题,你在.env中设置了你的数据库配置吗?
  • 感谢您的反馈,发布 3 个不同的代码标签在 stackoverflow 上不起作用,所以我制作了一个 Pastebin 供您查看:pastebin.com/dWv6YxEq 数据库配置正确,因为 POST方法已经适用于将新项目添加到数据库中。
  • 您的路线是/complaints,但您访问了图片中的/

标签: php laravel tinker


【解决方案1】:

您没有路由到控制器中的正确功能。试试这个

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

【讨论】:

    【解决方案2】:

    你应该试试这个:

    你的控制者

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

    您的观点 (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
    

    【讨论】:

      【解决方案3】:

      正如@amirhosseindz 所说
      当您访问此网址时:http://127.0.0.1:8000/complaints 它会起作用,因为您正在点击

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

      但是当你访问这个网址时:http://127.0.0.1:8000

      您正在执行此操作:

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

      $complaints 不存在的地方

      【讨论】:

      • 谢谢,视图不包括投诉,所以他们没有出现。
      【解决方案4】:

      试试下面的另一种语法:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-19
        • 1970-01-01
        • 2012-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多