0

enter image description herei am trying to get all messages that are sava in messages table in database but an error accured.

message.blade.php:

    <div class="sms">
<ul>
        @foreach($messages as $message)
            <li class="list-group-item"> {{$message->user->name}} : {{$message->message}}
                @if($message->user_id === Auth::user()->id)
                    <div class="action">
                        <a href="/delete/messages/{{$message->id}}">
                            <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                        </a>
                        /
                        <a href="/message/edit/{{$message->id}}">
                            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                        </a>
                    </div>
                @endif
            </li>
        @endforeach
</ul>
</div>

Controller:

public function GetMessages(){
    $messages = Messages::all();
    return view('message')->with('messages',$messages);
}

MessagesModel:

    class Messages extends Model
{
    protected $table = 'messages';
    protected $fillable = ['message','user_id'];
    protected $timestamp=false;

    public function user()
    {
        return $this->hasOne('App\User', 'id', 'user_id');
    }
}
Haider
  • 99
  • 11

1 Answers1

1

You should always perform checks on relationships unless you are confident a user will always be assigned to a message.

{{ ($message->user) ? $message->user->name : 'No User' }}
Devon
  • 30,524
  • 9
  • 46
  • 78
  • It's a crutch ) we need to see Messages model to udnerstand what happend – mcklayin May 08 '17 at 11:32
  • Why do you need to see their model? It could just be that one of the messages has no user_id in the database, not a hard concept.. – Devon May 08 '17 at 11:32
  • You could be right, of course, but according to code if no user, we need to remove\hide
  • by checking you codnition above
  • – mcklayin May 08 '17 at 11:35
  • Likely not. `$message->user_id === Auth::user()->id` will never evaluate to true if `$message->user_id` is null, since `Auth::user()->id` can usually never be null. – Devon May 08 '17 at 11:38