Laravel:试图获得非对象的属性

时间:2016-11-07 09:44:20

标签: laravel

我尝试制作一个社交网站类型的项目并尝试在用户登录时删除帖子,并且只允许他删除帖子,并且只能喜欢和不喜欢其他帖子。 但是,当我试图删除它时:它显示错误 -

Trying to get property of non-object

并且,在此编辑之前。当有人能够删除任何人的帖子时,代码为:

public function getDeletePost($post_id){

    $post = Post::where('user_id',$post_id)->first();

    if (Auth::user() != $post->user) {
        return redirect()->back();
    }

    if ($post != null) {
        $post->delete();
        return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
    }

    return redirect()->route('dashboard')->with(['message'=> 'Wrong ID!!']);
}

它只显示:"错误的ID !!"每次都不要删除帖子。

用户列的列:id,email,password posts表的列:id,created_at,updated_at,body,user_id

并且,posts表的user_id链接到users表的id。

添加了dd(Auth :: user(),$ post):

User {#183 ▼
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [▶]
#original: array:7 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
+exists: true
+wasRecentlyCreated: false
}
null

这里有什么问题?

包含删除按钮的部分代码:来自dashboard.blade.php:

<div class="interaction">
                <a href="#">Like</a> |
                <a href="#">Dislike</a> 
                @if(Auth::user() == $post->user)
                |
                <a href="#">Edit</a> |
                <a href="{{route('post.delete',['post_id=>$post->id'])}}">Delete</a> 
                @endif
            </div>

3 个答案:

答案 0 :(得分:1)

您正试图从null获取数据,因此会导致错误。只需将$post != null添加到第一个if,它就会按预期运行:

public function getDeletePost($post_id){

    $post = Post::where('user_id',$post_id)->first();

    if ($post != null && Auth::user() != $post->user) {
        return redirect()->back();
    }

    if ($post != null) {
        $post->delete();
        return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
    }

    return redirect()->route('dashboard')->with(['message'=> 'Wrong ID!!']);
}

答案 1 :(得分:0)

我建议您使用firstOrFail()而不是first()作为:

$post = Post::where('user_id',$post_id)->firstOrFail();

如果您使用firstOrFail(),则会确认您的$post对象是模型对象,而不是null

firstOrFail()方法将检索查询的第一个结果;但是,如果未找到任何结果,将抛出Illuminate \ Database \ Eloquent \ ModelNotFoundException。因此,您必须永远不需要if检查。

答案 2 :(得分:0)

被修改

 public function getDeletePost($post_id)
    {
        $post = Post::find($post_id);
        if ($post) {
            if (auth()->user()->id != $post->user_id) {
                return redirect()->back();
            }
            $post->delete();
            return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!!']);
        }
        return redirect()->route('dashboard')->with(['message' => 'Wrong ID!!']);

    }