Laravel - Property [comment] does not exist on this collection instance - php

i have a problem with laravel model relationship. The codes are as follows:
Route:
Route::get('/customers','Back\CustomerController#index')->name('admin.customer');
Models\Customer.php:
class Customer extends Model{
public function getData(){
return $this->hasMany('App\Models\Datapanel','name','name');
}
}
Models\Datapanel.php:
class Datapanel extends Model{
//
}
CustomerController.php:
class CustomerController extends Controller{
public function index(){
$customers=Customer::orderBy('created_at','desc')->get();
return view('back.customer',compact('customers'));
}
}
customer.blade.php:
#foreach ($customers as $customer)
<div class="tab-pane" id="{{$customer->name}}" role="tabpanel">
{{$customer->getData}} //this line working and calling all data of the same name, but in array format.
{{$customer->getData->comment}} //this line is what I want, but it doesn't work and gives the error Property [comment] does not exist on this collection instance
{{$customer->getData->first()->comment}} //this line working, but calling first data and i want all the data of the same name.
{{$customer->getData->all()->comment}} //I wish there was something like but it donesn't work.
</div>
#endforeach

Since getData is returning a HasMany relationship it will be a collection and not a single record. So need to loop over the collection to display data. See below
#foreach ($customers as $customer)
<div class="tab-pane" id="{{$customer->name}}" role="tabpanel">
<!-- Loop over each record in $customer->getData -->
#foreach($customer->getData as $data)
{{ $data->comment }}
#endforeach
</div>
#endforeach

Related

Laravel - multiple controllers in single view

I'm trying to code a simple event page. This page should display a particular event and it's features (including other info not relevant for the problem).
I've tried a couple different approaches with no luck, this is the approach I feel like I might be closet to success with, any suggestions?
I can provide other extracts of code if you think the problem lies elsewhere but I think my problem lies within these 7 files.
The current error I have is "Property [features] does not exist on this collection instance." and point to the EventController show() function.. if anyone could help I'd greatly appreciate it.
web.php
Route::get('cards/{id}', 'CardController#show');
Route::get('event/{id}', 'EventController#show');
event.blade.php
<h1 class="big-title">
</h1>
<section id="events">
#each('partials.event', $event, 'event')
</section>
(partials) event.blade.php
<header>
<h2 class="event-name fsb">
{{ $event->name }}
</h2>
</header>
<p class="event-description pdl1em">
{{ $event->description }}
</p>
<ul class="event-dates pdl1em">
<ul>
#each('partials.features', $event_features, 'feature')
</ul>
</ul>
Event.php
class Event extends Authenticatable
{
public function features() {
return $this->hasMany('App\Models\EventFeature');
}
}
EventFeature.php
class EventFeature extends Authenticatable
{
public function event() {
return $this->belongsTo('App\Models\Event');
}
}
EventController
class EventController extends Controller
{
public function show($id)
{
$event = DB::table('event')->where('id', $id)->get();
return view('pages.event', ['event' => $event, 'features' => $event->features]);
}
}
EventFeatureController
class EventFeatureController extends Controller
{
public function show($id)
{
$event_features = DB::table('event_features')->where('id', $id)->get();
return view('pages.event', ['event' => $event_features->eventClass, 'features' => $event_features]);
}
public function list($event_id)
{
if (!Auth::check()) return redirect('/login');
$event_features = DB::table('event_features')->where('event_id', $event_id)->orderBy('id')->get();
return view('pages.event', ['event_features' => $event_features]);
}
}
When you want to retrieve a single item, use find($id) or first() to retrieve an instance of the model. When you call get() you get a collection of an array with the instances inside it.
When using DB::table('events') you dont get as a result an instance of the model, you get a generic object instance => you can't use Model class defined methods like relations and such. use the model directly instead Event::where(...
Change your method to
class EventController extends Controller
{
public function show($id)
{
$event = Event::findOrFail($id);
return view('pages.event', ['event' => $event, 'features' => $event->features]);
}
}

Cant get Property from the model realtion Laravel

I got an issue when i use fooreach loop with 3 model realtion in 1 view
This is my Thread model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
protected $primaryKey = "id_threads";
public function user(){
return $this->belongsTo('App\User','id_users');
}
protected $fillable = [
'id_users', 'threads',
];
public function comment(){
return $this->hasMany('App\Comment','id_threads');
}
}
This is my Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $primaryKey = 'id_comments';
public function thread(){
return $this->belongsTo('App\Thread','id_threads');
}
public function users(){
return $this->belongsTo('App\User');
}
protected $fillable = [
'id_threads', 'id_users', 'comments','status'
];
}
This is my index controller
public function index()
{
$user = Auth::user();
$comment = Comment::all();
//Threads
$threads = Thread::orderBy('created_at','desc')
->get();
$hitung = $threads->where('id_users', '=',$user->id);
return view('/home',compact('threads','hitung','comment'));
}
And this is piece of my view
#foreach ($threads as $thread)
<div class="media-body">
<h5 class="mb-0">{{$thread->user->name}}</h5>
<div class="card-date mb-2">
{{date('F d, Y', strtotime($thread->created_at))}} at {{date('g : ia', strtotime($thread->created_at))}}
</div>
<input type="hidden" name="$id_threads" value="{{$thread->id_threads}}">
{{$thread->threads}}
<div class="card-delete mt-5">
#if (Auth::user()->id==$thread->id_users)
Delete
#else
#endif
</div>
<hr>
<div class="media comment mt-3">
<a class="mr-3" href="#">
{{$thread->comment->comments}}
The Error comes when i want to show comment
{{$thread->comment->comments}}
And an error like this appears
Property [comments] does not exist on this collection instance. (View: D:\Jendro\Project Laravel\projectCO\resources\views\home.blade.php)
But when i just call the object only, like this
{{$thread->comment}}
Thats no error appears, in my view a data set appears from the Comment model
[{"id_comments":6,"id_threads":54,"id_users":2,"comments":"asdqweasd","created_at":"2020-06-29 08:58:53","updated_at":"2020-06-29 08:58:53","status":"comment"}]
It was same when i use to call user object, but threse no problem with user object when i call property of user's object
I was stuck in this issue, does anyone have solution for this issue ?
You will not be able to access this way, as this is a hassle. There is not one record, but an array of records. You need to twist $ thread->comments and get comments from it.
But if $ thread->comment should always be a single entry, then use hasOne in Thread class instead of hasMany

How to pass parameter in Laravel Relationship Function within blade?

Student.php
It has many fees
class student extends Model{
public function fees($round){
return $this->hasMany(fee::class)->where('payment_round','=',$round);
}
}
Fee.blade.php
#foreach($student->fees("parameter") as $fee)
{{$fee->myproperty}}
#endforeach
How I can pass a parameter to $student->fees("parameter")?
You can keep relationship as simple as possible and add a second method which uses that to get the data you want :
<?php
class student extends Model{
public function fees(){
return $this->hasMany(fee::class);
}
public function getFeeByRound($round)
{
return $this->fees()->where('payment_round','=',$round)->get();
}
}
And then you can use this as :
#foreach($student->getFeeByRound($parameter) as $fee)
{{ $fee->myproperty }}
#endforeach
Try something like that:
#foreach($student->fees($parameter)->get() as $fee)
{{ $fee->myproperty }}
#endforeach
I think you had confused the collection of related models fees with the query constructor fees().

Laravel - cannot use Eloquent model method

The table distributor_requisition_items has the columns :requisition_id,product_id ,measuring_unit_id,quantity
In the model DistributorRequisition.php, I have:
class DistributorRequisition extends Model
{
public function items()
{
return $this->belongsToMany('App\Product','distributor_requisition_items',
'requisition_id','product_id')->withPivot('measuring_unit_id','quantity');
}
}
In the controller I have :
class CurrentInventoryController extends Controller
{
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
$distributor_requisitions_all= $distributor_requisition->items;
// this line produces an error
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisitions_all','stores',.....));
}
}
In the distributor-inventory.blade.php, I have :
#foreach($distributor_requisitions_all as $aP)
{{$aP->items->measuring_unit_id}}
#endforeach
I get the following error :
Exception in Collection.php line 1527: Property [items] does not exist on this collection instance.
in Collection.php line 1527 at Collection->__get('items') in CurrentInventoryController.php line 64
And the line 64 in the controller has :
$distributor_requisitions_all= $distributor_requisition->items;
So how to use the eloquent model method items in the controller so that I can access the distributor_requisitions_all variable in the view to extract values from it ?
use with() method instead of get().
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::with('items');
return view('admin.current_inventory.distributor-inventory', ['distributor_requisitions_all' => $distributor_requisition]);
}
$distributor_requisition=DistributorRequisition::get(); is a collection of Model DistributorRequisition, while items is a method inside the model that is why it is giving you an error .. you can't directly call a Model method from a collection .. and to solve your issue what you have to do is
in your function
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisition','stores',.....));
}
and in your view
#foreach($distributor_requisition as $aP)
// {{ $aP->items->measuring_unit_id }}
// that will give you error since $aP->items is another collection of many model item what you can do is add another loop
#foreach($aP->items as $item)
$item->pivot->measuring_unit_id }}
#endforeach
#endforeach

Laravel not passing query result from controller to view

Laravel version 5.2
My controller file:
<?php
namespace App\Http\Controllers;
use App\questions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
class Dashboard extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function fetchQuestions() {
//
}
public function index(){
$listQuestions=Auth::user()->questions()->pluck('question')->all();
//dd($listQuestions);
return view('forms.question',compact('listQuestions'));
}
}
My views file
<ul>
#foreach ($listQuestions as $q)
<li>{{ $q }}</li>
#endforeach
</ul>
$listQuestions isnt getting passed to the view.
But on dd($listQuestions) from view & controller file, I get this
array:2 [▼
0 => "some question"
1 => "another question"
]
It shows empty view page, no errors or output
What am I missing here?
pluck() method retrieves values by keys. You want to get a collection:
$listQuestions = Auth::user()->questions()->get();
$q is an object, so you need to get a property, i.e. question:
#foreach ($listQuestions as $q)
<li>{{ $q->question }}</li>
#endforeach
You can also pass a variable to a view like this
return view('forms.question')
->with('listQuestions' , $listQuestions)
Now i believe you're just passing the string 'listQuestions' over to the view, so it can't iterate over it. Hence the empty view.
Change your
return view('forms.question',compact('listQuestions'));
To
return view('forms.question',['listQuestions'=> $listQuestions]);
That should work

Categories