繁体   English   中英

试图在 laravel 8 中获取非对象的属性“users_id”

[英]Trying to get property 'users_id' of non-object in laravel 8

我在我的应用程序的 controller 中收到此错误,我无法修复它,如果有人帮助我,我将不胜感激。 我给你代码:奇怪的是我的 model 中的关系是正确的

错误:试图获取非对象的属性“users_id”

Controller - Model - 路线 - 查看

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Comment;

class CommentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function save(Request $request){

        //Validacion
        $validate = $this->validate($request, [
            'image_id' => 'required|integer',
            'content' => 'string|required'
        ]);

        //Recoger datos
        $user = \Auth::user();
        $content = $request->input('content');
        $image_id = $request->input('image_id');

        //Asigno los valores a mi objeto
        $comment = new Comment;
        $comment->users_id = $user->id;
        $comment->images_id = $image_id;
        $comment->content = $content;
       
        //guardar en la base de datos
        $comment->save();

        return redirect()->route('image.detail', [
            'id' => $image_id
        ])->with([
            'message' => 'Haz hecho un comentario'
        ]);

    }

    public function delete($id){
        //Conseguir datos del usuario identificado
        $user = \Auth::user();

        //Conseguir objeto del comentario
        $comment = Comment::find($id);

        //Comprobar si soy el dueño del comentario o de la publicacion
        if ($user && ($comment->users_id == $user->id || $comment->images->users_id == $user->id)) {
            $comment->delete();
            return redirect()->route('image.detail', ['id' => $comment->images->id])
                        ->with([
                            'message' => 'Comentario eliminado'
                        ]);
        }else{
            return redirect()->route('image.detail', ['id' => $comment->images->id])
                        ->with([
                            'message' => 'Comentario NO eliminado!'
                        ]);
        }

    }
}

型号

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $table = 'coments';

    public function user()
    {
        return $this->belongsTo(User::class, 'users_id');
    }

    public function images()
    {
        return $this->belongsTo(Image::class, 'images_id');
    }
}

路线

Route::get('/comment/delete/{id}', [App\Http\Controllers\CommentController::class, 'delete'])->name('comment.delete');

查看

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            @include('includes.message')
            <div class="card pub_image pub_image_detail">
                <div class="card-header">
                    @if($image->user->image)
                    <div class="container-avatar">
                        <img src="{{route('user.avatar', ['filename' => $image->user->image])}}" class="avatar">
                    </div>
                    @endif
                    <div class="data-user">
                            {{$image->user->name.' '.$image->user->surname}}
                            <span class="nickname">
                                {{' | @'.$image->user->nick}}
                            </span>
                    </div>
                </div>
                <div class="card-body">
                    <div class="image-container">
                        <img src="{{ route('image.file', ['filename' => $image->imagen_path]) }}" alt=""/>
                    </div>
                    
                    <div class="description">
                        <span class="nickname">{{'@'.$image->user->nick}}</span> 
                        <span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($image->created_at)}}</span>
                        <p>{{$image->description}}</p>
                    </div>

                    <div class="likes">
                        <img src="{{asset('/img/corazon-negro.png')}}" alt=""/>
                    </div>
                    <div class="clearfix"></div>
                    <div class="comments">
                        <h4>Comentarios ({{count($image->comments)}})</h4>
                        <hr>

                        <form action="{{route('comment.save')}}" method="POST">
                            @csrf 
                            <input type="hidden" name="image_id" value="{{$image->id}}">
                            <p>
                                <textarea name="content"  id="" cols="30" rows="10" class="form-control box-comment {{$errors->has('content') ? 'is-invalid' : ''}}"></textarea>
                                @error('content')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror
                            </p>
                            
                            
                            <button type="submit" class="btn btn-success">
                                Enviar
                            </button>
                        </form>
                        @foreach($image->comments as $comment)
                            <div class="comment">
                                <span class="nickname">{{'@'.$comment->user->nick}}</span> 
                                <span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($comment->created_at)}}</span>
                                <p>{{$comment->content}}</p>

                                @if(Auth::check() && ($comment->users_id == Auth::user()->id || $comment->images->users_id == Auth::user()->id))
                                    <a href="{{route('comment.delete', ['id', $comment->id])}}" class="btn btn-sm btn-danger">
                                        Eliminar
                                    </a>
                                @endif

                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

如果我理解正确,并非每个评论都有图像,而且评论和图像使用一对多关系。 所以你应该修复这个检查:

... $comment->images->users_id == $user->id ...

添加外键和本地键以确保两列相互通信。

 public function user()
    {
        return $this->belongsTo(User::class, 'users_id', 'id'); //id or users_id  or whatever in your column. I assume , just maybe different column.
    }

然后不要忘记

    if ($comment->User) {
//some code here
    }

避免错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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