【问题标题】:Trying to get property 'id' of non-object (View: /home/alex/Desktop/laravel/cms/resources/views/posts/index.blade.php)试图获取非对象的属性“id”(查看:/home/alex/Desktop/laravel/cms/resources/views/posts/index.blade.php)
【发布时间】:2021-10-12 13:00:03
【问题描述】:

我发现这两行导致问题,但我不知道如何重写它们以继续

                            <a href="{{ route('categories.edit', $post->category->id ) }}">
                               {{ $post->category->name }} 
                            </a>

这是我的帖子/index.blade.php

@extends('layouts.app')

@section('content')
<div class="d-flex justify-content-end mb-2">
    <a href="{{ route('posts.create') }}" class="btn btn-success float-right">Add Post</a>        
</div>

<div class="card card-default">
    <div class="card-header">Posts</div>
    <div class="card-body">
        @if ($posts->count()>0)
        <table class="table">
            <thead>
                <th>Image</th>
                <th>Title</th>
                <th>Category</th>
                <th></th> 
                <th></th>              
                <tbody>
                    @foreach($posts as $post)
                    <tr>
                        <td>
                            <img src="{{ asset('storage/'.$post->image) }}" width="120px" height="60px" alt="">
                        </td>
                        <td>
                            {{ $post->title }}
                        </td>
                        <td>
                            <a href="{{ route('categories.edit', $post->category->id ) }}">
                               {{ $post->category->name }} 
                            </a>
                        </td>
                        @if($post->trashed())
                        <td>
                            <form action="{{ route('restore-posts', ['post' => $post['id']]) }}" method="POST">
                                @csrf
                                @method('PUT')
                                <button type="submit" class="btn btn-info btn-sm">Restore</button>
                            </form>
                        </td>
                        @else
                        <td>
                            <a href="{{ route('posts.edit',  ['post' => $post['id']]) }}" class="btn btn-info btn-sm">Edit</a>
                        </td>
                        @endif

                        <td>
                            <form action="{{ route('posts.destroy', ['post' => $post['id']]) }}" method="POST">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger btn-sm">
                                    {{ $post->trashed() ? 'Delete' : 'Trash' }}
                                </button>

                            </form>
                        </td>                        
                    </tr>
                    @endforeach
                </tbody>
            </thead>
        </table>
        @else 
            <h3 class="text-center">
                No Posts Yet
            </h3>
        @endif
    </div>
</div>
@endsection

这是我的控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostRequest;
use App\Post;
use App\Category;
// use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Posts\UpdatePostRequest;

class PostsController extends Controller
{
    public function __construct(){
        $this->middleware('verifyCategoriesCount')->only(['create','store']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('posts.index')->with('posts', Post::all());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
       return view('posts.create')->with('categories', Category::all());

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $image = $request->image->store('posts');
        Post::create([
            'title' => $request->title,
            'description' => $request->description,
            'content' => $request->content,
            'image' => $image,
            'published_at' => $request->published_at,
            'category_id' => $request->category
        ]);
        session()->flash('success', 'Post created succesfully.');
        return redirect(route('posts.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        return view('posts.create')->with('post', $post)->with('categories', Category::all());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatePostRequest $request, Post $post)
    {
        $data = $request->only(['title', 'description', 'published_at', 'content']);
        // check if new image
        if($request->hasFile('image')){
            // upload it
            $image = $request->image->store('posts');
            // delete old one
            $post->deleteImage();
            $data['image'] = $image;
        }
        // update attributes
        $post->update($data);
        // falsh message
        session()->flash('success', 'Post updated succesfully');
        // redirect user
        return redirect(route('posts.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post = Post::withTrashed()->where('id', $id)->firstOrFail();
        if($post->trashed()){
            $post->deleteImage();
            $post->forceDelete();
        }else{
            $post->delete();
        }
        session()->flash('success', 'Post deleted succesfully.');
        return redirect(route('posts.index'));
    }

    /**
     * Display a list of all trashed posts
     *
     * @return \Illuminate\Http\Response
     */    
    public function trashed(){
        $trashed = Post::onlyTrashed()->get();
        return view('posts.index')->withPosts($trashed);
    }

    public function restore($id){
        $post = Post::withTrashed()->where('id', $id)->firstOrFail();    
        $post->restore();
        session()->flash('success', 'Post restored succesfully');
        return redirect()->back();
    }
}

【问题讨论】:

  • 首先检查dd($post-&gt;category),它包含一个与价值相关的帖子

标签: php laravel


【解决方案1】:

您的 $post-&gt;category 不是对象,这就是出现此错误的原因。

试试

dd($post->category)

你会看到里面有什么。这将帮助您调试真正的问题。

【讨论】:

    【解决方案2】:

    首先使用以下方式预先加载关系(以防止 N+1 问题):

    public function index()
    {
        $posts = Post::with('category')->get();
        return view('posts.index')->with('posts', $posts);
    }
    

    如果你仍然得到错误,可能是因为你试图查看的帖子没有category,所以关系是null。因此,当您尝试获取类别 id 时,它会抛出 null 没有 id 的异常。

    你可以通过检查之前是否有任何类别来解决它:

    @if($post->category)
        <a href="{{ route('categories.edit', $post->category->id ) }}">
           {{ $post->category->name }}
        </a>
    @endif
    

    【讨论】:

      【解决方案3】:

      在将模型注入视图之前,在控制器中使用预先加载。

      $post->load('category');
      

      确保每个帖子都与类别相关。

      【讨论】:

        猜你喜欢
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2020-11-15
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 2018-07-04
        相关资源
        最近更新 更多