简体   繁体   中英

Laravel: Can't access Eloquent relationship

I've made Post and User models and defined a one to many relationship between the two like so:

User.php

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'profile_picture',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function posts () {
        return $this->hasMany(Post::class,'post_author');
    }
}

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'post_title', 'post_content', 'post_author', 'post_type', 'created_at', 'updated_at',
    ];
    public function user() {
        return $this->belongsTo(User::class,'id');
    }
    public function postfields() {
        return $this->hasMany(PostField::class);
    }
}

Now, in my blog controller I compact the Post class into my blog view like so:

BlogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Post;

use App\User;

class BlogController extends Controller
{
    public function index(Post $post) {
        $blog_posts = Post::with('user')->where('post_type', '=', 'blog')->get();
        return view('blog', compact('blog_posts'));
    }
}

Now I attempt to access the relationship inside of the blog view:

@foreach ($blog_posts as $blog_post)
    <div class="post item">
        {{ $blog_post->post_title }}
        {{ $blog_post->post_content }}
        {{ $blog_post->user->name }}
    </div>
@endforeach

Everything appears as it should in the blog view when there is only one blog post in the database, however I get the following error when there is more than one:

ErrorException in 84794846d554b14eb937f08dfef09b6f1edd91c6.php line 43: Trying to get property of non-object (View: C:\\MAMP\\htdocs\\Biota-New\\resources\\views\\blog.blade.php)

Any help would be much appreciated.

Here's a DD of the $blog_posts variable:

Collection {#198 ▼
  #items: array:2 [▼
    0 => Post {#194 ▼
      #fillable: array:6 [▼
        0 => "post_title"
        1 => "post_content"
        2 => "post_author"
        3 => "post_type"
        4 => "created_at"
        5 => "updated_at"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:7 [▼
        "id" => 1
        "post_title" => "TEST"
        "post_content" => "Test post"
        "post_author" => 1
        "post_type" => "blog"
        "created_at" => "2016-10-08 14:20:07"
        "updated_at" => "2016-10-08 14:20:07"
      ]
      #original: array:7 [▼
        "id" => 1
        "post_title" => "TEST"
        "post_content" => "Test post"
        "post_author" => 1
        "post_type" => "blog"
        "created_at" => "2016-10-08 14:20:07"
        "updated_at" => "2016-10-08 14:20:07"
      ]
      #relations: array:1 [▼
        "user" => User {#199 ▼
          #fillable: array:4 [▼
            0 => "name"
            1 => "email"
            2 => "password"
            3 => "profile_picture"
          ]
          #hidden: array:2 [▼
            0 => "password"
            1 => "remember_token"
          ]
          #connection: null
          #table: null
          #primaryKey: "id"
          #keyType: "int"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:9 [▼
            "id" => 1
            "name" => "Sup3rL3on"
            "email" => "codeoncaffeine1@gmail.com"
            "password" => "$2y$10$b6pMtiKt0LcDCeRtTlVJzOL3BvD6Ru1TihbOhM7FOHUscW0daIwGC"
            "profile_picture" => "default-profile-picture"
            "account_type" => 1
            "remember_token" => null
            "created_at" => null
            "updated_at" => null
          ]
          #original: array:9 [▼
            "id" => 1
            "name" => "Sup3rL3on"
            "email" => "codeoncaffeine1@gmail.com"
            "password" => "$2y$10$b6pMtiKt0LcDCeRtTlVJzOL3BvD6Ru1TihbOhM7FOHUscW0daIwGC"
            "profile_picture" => "default-profile-picture"
            "account_type" => 1
            "remember_token" => null
            "created_at" => null
            "updated_at" => null
          ]
          #relations: []
          #visible: []
          #appends: []
          #guarded: array:1 [▼
            0 => "*"
          ]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▼
        0 => "*"
      ]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => Post {#195 ▼
      #fillable: array:6 [▼
        0 => "post_title"
        1 => "post_content"
        2 => "post_author"
        3 => "post_type"
        4 => "created_at"
        5 => "updated_at"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:7 [▼
        "id" => 6
        "post_title" => "TEST"
        "post_content" => "Test post"
        "post_author" => 1
        "post_type" => "blog"
        "created_at" => "2016-10-08 14:20:07"
        "updated_at" => "2016-10-08 14:20:07"
      ]
      #original: array:7 [▼
        "id" => 6
        "post_title" => "TEST"
        "post_content" => "Test post"
        "post_author" => 1
        "post_type" => "blog"
        "created_at" => "2016-10-08 14:20:07"
        "updated_at" => "2016-10-08 14:20:07"
      ]
      #relations: array:1 [▼
        "user" => null
      ]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▼
        0 => "*"
      ]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

Blog.blade.php

@extends('layouts.front-header')

@section('content')
<style>
    .hero-image {
        background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url(images/hero-2.jpg);
    }
</style>


<div class="hero-image hero-image-inner-page">
    <div class="hero-image-inner">
        <div class="text">
            <h1>Blog</h1>
        </div>
    </div>
</div>



<main>
    <section class="blog">
        <div class="container">
        <div class="posts">
        <div class="items">
            <!-- 
            <div class="post item">
                <h3 data-field="post_title"></h3>
                <p data-field="post_content"></p>
                <img src="http://fiddle-earth.com/updates/madsa/img/image00.png" alt="">
                <div class="post-data">
                    <img data-field="author_profile_picture" alt="">
                    <p>posted by <strong data-field="post_author"></strong> on <span data-field="post_date"></span></p>
                </div>
            </div> -->


            @foreach ($blog_posts as $blog_post)
                <div class="post item">
                    <h3 data-field="post_title">{{ $blog_post->post_title }}</h3>
                    <p data-field="post_content">{{ $blog_post->post_content }}</p>
                    <!-- <img src="http://fiddle-earth.com/updates/madsa/img/image00.png" alt=""> -->
                    <div class="post-data">
                        <img data-field="author_profile_picture" alt="">
                        @if($blog_post->user()!=null)
                            {{ $blog_post->user->name }}
                        @endif
                        <p>posted by <strong data-field="post_author"></strong> on <span data-field="post_date"></span></p>
                    </div>
                </div>
            @endforeach

        </div>
        <!-- <a href="#" class="items-load">Load more</a> -->
        </div>
        </div>
    </section>
</main>




<script src="assets/js/loadmore.js"></script>
<script>
$('.posts').loadmore({
    source: 'assets/js/json/blog-json.php',
    img: 'uploads/',
    step: 4
});
</script>
@endsection

As far as I can see, the User relation in the Post model is causing the exception. So, when you call:

{{ $blog_post->user->name }}

it can't find the user associated with that post. I am guessing that the foreign key for User table is not the same as guessed by Laravel:

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Comment model is not post_id, you may pass a custom key name as the second argument to the belongsTo method:

public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key');
}

So in your case, it would be something like this:

public function user()
{
    return $this->belongsTo('App\User', 'post_user_id'); //Replace post_user_id with the id convention you are using.
}

Update:

Thanks for the dd on your $blog_posts. I can see that the user is being fetched but it's not being called correctly. It's a function so you need to treat it as a function. Modify your blade file to retrieve the user like this:

 {{ $blog_post->user()->name }} 

This should get the valid user collection.

Update 2:

As I can see from the dump, the user relation from the second Post is null. Make sure it's not null when you are creating the post and to deal with it in the blade, wrap it in a null check:

 @foreach ($blog_posts as $blog_post) <div class="post item"> {{ $blog_post->post_title }} {{ $blog_post->post_content }} @if($blog_post->user()!=null) {{ $blog_post->user()->name }} @endif </div> @endforeach 

Update 3:

It actually is supposed to be called as an attribute rather than a function since it returns 'BelongsTo' when called as a function. Try the following now:

 @foreach ($blog_posts as $blog_post) <div class="post item"> {{ $blog_post->post_title }} {{ $blog_post->post_content }} @if($blog_post->user!=null) {{ $blog_post->user->name }} @endif </div> @endforeach 

I've reproduced the same issue here and this fixes it. Let me know if it works for you.

我没有发现错误尝试

composer dump-autoload

php artisan view:clear

Try out this:

instead of

@foreach ($blog_posts as $blog_post)
    <div class="post item">
        {{ $blog_post->post_title }}
        {{ $blog_post->post_content }}
        {{ $blog_post->user->name }}
    </div>
@endforeach

Use the following:

    @foreach ($blog_posts as $blog_post)
            <div class="post item">
                {{ $blog_post->post_title }}
                {{ $blog_post->post_content }}
                @foreach($blog_post->user as $user)
                    {{ $user->name }}
                @endforeach
    @endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM