I have this Contractor Model
public function ContractorDetails() { return $this->hasOne(ContractorDetails::class)->select('id', 'contractors_id'); }
And ContractorDetails Model
public function Contractors() { return $this->belongsTo(Contractors::class); }
I can retrieve all columns under the Contractors Model, but whenever I do this $contractors->ContractorDetails->id, it will show this error “Trying to get property ‘id’ of non-object” . however when I just use this $contractors->ContractorDetails, it is able to show this collection {“id”:6,”contractors_id”:24}
My controller looks like this
**$contractors = Contractors::orderby('name')->with('ContractorDetails')->get();**
My blade file
<tbody> @foreach($contractors as $contractor) <tr class="bg-white lg:hover:bg-gray-100 flex lg:table-row flex-row lg:flex-row flex-wrap lg:flex-no-wrap mb-10 lg:mb-0"> <td class="w-full lg:w-auto p-3 text-gray-800 text-center border border-b block lg:table-cell relative lg:static"> <span class="lg:hidden absolute top-auto left-0 bg-blue-200 px-1 py-1 text-xs font-bold"> Contractor Name</span> {{ $contractor->name }} </td> <td class="w-full lg:w-auto p-3 text-gray-800 text-center border border-b text-center block lg:table-cell relative lg:static"> <span class="lg:hidden absolute top-auto left-0 bg-blue-200 px-1 py-1 text-xs font-bold">Status</span> <span class="{{$contractor->status == 0 ? 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-green-800' : 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800' }}"> {{$contractor->status == 0 ? 'onHold' : 'Approved' }}</span> </td> <td class="w-full lg:w-auto p-3 text-gray-800 text-center border border-b text-center block lg:table-cell relative lg:static"> <span class="lg:hidden absolute top-auto left-0 bg-blue-200 px-1 py-1 text-xs font-bold">Actions</span> <x-jet-button wire:click="{{ route('ContractorID', [$contractor->ContractorDetails->id])}}" wire:loading.attr="disabled"> {{ __('EDIT') }} </x-jet-danger-button> <x-jet-danger-button wire:click="confirmContractorDeletion( {{$contractor->id }})" wire:loading.attr="disabled"> {{ __('Delete') }} </x-jet-danger-button> </td> </tr> @endforeach </tbody>
Any help would be greatly appreciated
Advertisement
Answer
Found a fix.
I create another function under my Contractors Model
public function getContractorDetailsAttribute() { return $this->ContractorDetails()->pluck('id')->first(); }
Now I can get the ID from the ContractorDetails Model with this
$contractors->ContractorDetails