首页 > 解决方案 > 未传递对象值

问题描述

我正在使用 Laravel 5.6 并且在将数据传递到我的刀片文件时遇到问题。

博客控制器:

namespace App\Http\Controllers;

use App\Mail\Practice;
use App\Mail\Mailable;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;

class BlogController extends Controller
{
  public function getSingle($slug){
    // Fetch from the DB based on Slug --first stops after one, get pulls everything
  $post = Post::where('slug', '=', $slug)->first();
  print_r($slug);

  // return the view and pass in the post object
  return view('blog.single')->withPost($post);

 }
}

single.blade.php:

@extends('main')

@section('title', "| $post->title")

@section('content')


  <div class="row">
   <div class="col-md-8 col-md-offset-2">
    <h1>{{ $post->title}}</h1>
    <p>{{ $post->body }}</p>
</div>


@停止

我在数据库(MySQL)中验证了名称和拼写。如果我dd($slug)print_r($slug)结果是正确的。

但是,如果我做同样的事情但使用$titleor$body它返回错误

试图获取非对象的属性(查看:/Users/jesseburger/myproject/resources/views/blog/single.blade.php)

我已经能够通过使用来验证它是否拉了一个空数组,print_r($post)但不知道为什么。

print_r($post)产量:

Illuminate\Database\Eloquent\Collection 对象 ( [items:protected] => Array ( ) )

目前路线:

Route::get('blog/{slug}', [
    'as' => 'blog.single', 
    'uses' => 'BlogController@getSingle'
])->where('slug', '[\w\d\-\_]+');

标签: mysqllaravelcontrollerlaravel-blade

解决方案


您的退货声明不正确,您需要更改此行:

return view('blog.single')->withPost($post);

对此,它应该可以解决您的问题。

return view('blog.single')->with('post', $post);

推荐阅读