I'm getting the
ErrorException: Trying to get property of non-object
I'm trying to display all the relationship that is link using this function. The relationship is ->
-Card can have many notes, Notes only have one card. -Each notes contain only one user, User contain only one card. My code is:
Note
class Note extends Model
{
protected $fillable = ['body'];
public function cards()
{
return $this->belongsTo(Card::class);
}
public function users()
{
return $this->belongsTo(User::class,'id');
}
}
User
class User extends Authenticatable
{
use Notifiable;
public function note()
{
return $this->belongsTo(Note::class);
}
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
Card
class Card extends Model
{
public function notes()
{
return $this->hasMany(Note::class);//relationship
}
public function addNote(Note $note)
{
return $this->notes()->save($note);
}
}
CardsController
class cardsController extends Controller
{
public function index()
{
$cards = Card::all();
return view('cards.index',compact('cards'));
}
public function show(Card $card)
{
$card->load('notes.user'); **The Error is here.**
$return $card;
return view('cards.show',compact('card'));
}
}
NotesController
class notesController extends Controller
{
public function store(Request $request, Card $card)
{
$card->addNote(
new Note($request->all())
);
return back();
}
public function edit(Note $note)
{
return view('notes.edit',compact('note'));
}
public function update(Request $request, Note $note)
{
$note -> update($request -> all());
return back();
}
}
1. notes table
$card->load('notes.user'); -when I just put (notes) in the cardControllers
function, it will appear all data that link from card and notes table. -but when I try to add (notes.user) it said that trying to get non property object. Am I missing something?
This is a very common and self explanatory error, it comes when you are trying to access a class property which doesn't really exist.
To avoid this, use isset() before access the property.
try like this in notes controller $notes=DB::table('notes')->get(); return view('cards.show')->with('notes',$notes);
it will work.
In view if u want display use @foreach($notes as $row) {{$row->user_id}} @endforeach
`
$card->load('notes.user');
This means you are trying to load two relations from Card
model - notes and user. Looking at your model user
relation is missing from your Card
model. Also, in your note model you've mentioned it as `users'. It would be better if you use singular term across the app.
Since no relation has been loaded, it's obvious to get property of non-object
while accessing $model->relation
or $model->relation->property
.