I'm using Laravel 5.4 in a project and I'm having trouble getting the information from related models to display correctly. The program is for a small veterinary clinic where pet owners are first registered, and then each of their pets (each owner can have many) is added. In turn, each pet can have multiple consults, vaccinations, documents, etc. Because there are a minimum of three layers involved for each, I though it would be best to keep the url/paths as simple as possible, so instead of a pet's url being /owner/1/pet/1, I kept it as /pet/1, which I believe is why nothing I've tried seems to work as it should (all examples I've seen follow the first path).
Pets Controller
I can create new pets with no problem, all their information is saved and can be edited as well. The problem is when I try to view each of them, some all look as they should with their respective owner information, but others (the newest) give me an error Trying to get property of non-object (View: D:\xampp\htdocs\veterinary\resources\views\pets\show.blade.php)
public function index()
{
$pets = Pet::all();
$owner = Owner::find($pets);
return view('pets.index', compact('owner', 'pets'));
}
public function store(Request $request)
{
$pet= new Pet;
//////////////
$pet->save();
}
public function show(Pet $pet)
{
$owner = Owner::find($pet);
return view('pets.show', compact('owner', 'pet'));
}
Owners Controller
I can show the owner's information with no problem, but I can't seem to be able to retrieve a list of the pets registered under their name. I've tried doing it different ways and have gotten different results (no errors but no pets found, object is null, query could not be converted to string, etc.). I left the functions with the commented ways I've tried so far.
public function index()
{
$owners = Owner::all();
return view('owners.index', compact('owners'));
}
public function getPets($id)
{
$pets = Pet::owner($id)->get();
return $pets;
}
public function store(Request $request)
{
$owner = new Owner;
//////////////
$owner->save();
}
public function show(Owner $owner)
{
//$pets = Owner::pets();
//$owner = Owner::find($owner->id_owner);
//$pets = $this->getPets($owner->owner_id);
//$pets = Pet::find($owner)->owner()->where('id_owner', '=', $owner->id_owner)->get();
$pets = DB::table('pets')->where('owner_id','=',$owner->id_owner);
$pets = Pet::find($pets)->owners;
return view('owners.show', compact('owner', 'pets'));
}
Pets Model
public function owner()
{
return $this->belongsTo('App\Owner');
}
Owners Model
public function pets()
{
return $this->hasMany('App\Pet');
}
Apologies for the extremely long post, I'm just having a hard time figuring out how to properly achieve all of this. I've tried all sorts of different ways over the last couple of days, ending up with partially working outcomes or straight up messing everything up. Thanks for your help!
via pzl-kleur