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
Related
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]);
}
}
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
I am trying to show the related applications to abstract, I have used the code below but I am getting this error
Array to string conversion
My controller
public function show($A_ID){
$abstract = Project::find($A_ID);
// I believe the issue is caused by the line below but I am not sure what is wrong about it
$applications = Application::find($A_ID);
return view('Abstracts.show')->with('abstract', $abstract)
->with($applications);
}
EDIT: (add model v1.0 and v1.1)
My model (v1.0) which show the error of Array to string conversion
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Traits\HasCompositePrimaryKey;
class Application extends Model{
//Table name
protected $table = 'student_application';
//composite key
protected $primaryKey = array('A_ID', 'S_ID');
protected $fillable = ['S_Justification' ];
public $incrementing = false;}
My edited Model (V1.1)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\HasCompositePrimaryKey;
class Application extends Model{
use HasCompositePrimaryKey;
//Table name
protected $table = 'student_application';
//composite key
protected $primaryKey = array('A_ID', 'S_ID');
protected $fillable = ['S_Justification' ];
public $incrementing = false;}
I want to note that the composite key is declared using this answer number two with currently 59 votes
For more information here is my view
#if (count($applications)>0)
#foreach ($applications as $application)
<tr>
<td><h5>{{$application->S_ID}}</h5></td>
</tr>
#endforeach
#else
<p> This project has no applications </p>
#endif
You are passing string to view.
return view('Abstracts.show')->with(['abstract'=> $abstract)];
give it a try.
Edit:
Or you can use like that.
with(array('order' => function($query)
Anyway you need to pass array in here. If you are just want to use ->with('abstract'); you need to add abstract function. For example:
public function deliveries() {
// this might be $this->hasOne... depends on what you need
return $this->hasMany('Abstracts', 'conditions', 'id')->where('foo', '!=', 'bar');
}
$applications is an object in your controller but you are accesing $applications as collection in your view file. You may try this:
$applications = Application::where('id', $A_ID)->get();
return view('Abstracts.show', compact('abstract', 'applications'));
I have two tables one called "Events" and another one "Dependences", a dependency can have several events, that is the relation between them, what I try to do is show the data of an event, but also show the data of the dependency to which is related.
This is my controller where I bring the event:
class WelcomeController extends Controller
{
public function evento($slug){
$event = Event::where('slug', $slug)->first();
return view('evento', compact('event'));
}
This is the event model:
class Event extends Model
{
protected $table = 'events';
protected $fillable = [
'admin_id', 'dependence_id', 'place_id', 'name', 'slug', 'excerpt', 'body', 'status', 'file'
];
public function dependences(){
return $this->belongsTo('App\Dependence', 'dependence_id');
}
dependence model:
class Dependence extends Model
{
protected $table = "dependences";
protected $fillable = [
'name', 'slug'
];
public function events(){
return $this->hasMany('App\Event');
}
so I try to show it in the view:
#foreach($event->dependences as $dependence)
<a href="#">
{{$dependence->name}}
</a>
#endforeach
but I get this error: Trying to get property 'name' of non-object
these are the tables in the database:
enter image description here
the routes are fine, but I do not know what the problem is, I hope for your help, thank you very much.
There is only one dependency for every event. So you no need to use foreach.
$events->dependency->name
And you should change the relationship name from dependences to dependency.
class Event extends Model
{
public function dependency()
{
return $this->belongsTo('App\Dependence', 'dependence_id');
}
}
In view:
#foreach($events as $event)
{{ $event->dependency->name }}
#endforeach
You should access directly, as:
$event->dependence->name;
Since, belongsTo relationship brings one item.
Also add a check to see if the object is null, as in:
#if($event->dependece)
$event->dependence->name;
#endif
You could also use an #else in case you want to manage the null case somehow
I'm building a Laravel 5.6.27 application in PHP 7.2.5 where assignments can be created and given a task (task_id) and a person (person_id) to assign them to (along with dueDate, etc.). I'm getting this error when I try to load the page:
Class 'App/Person' not found (View: /Users/mmickelson/Sites/sacrament/resources/views/assignments/index.blade.php)
Here's the index.blade.php file:
#extends('layouts.master')
#section('title', 'Assignments')
#section('content')
<table>
#foreach($assignments as $assignment)
<tr>
<td>{{$assignment->person->firstName}}</td>
</tr>
#endforeach
</table>
#endsection
I'm showing only the firstName of the person to help make it as simple as possible and isolate the issue.
Here's the (beginning of) the AssignmentController.php:
use App\Assignment;
use App\Task;
use App\Person;
use Illuminate\Http\Request;
class AssignmentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index() {
$assignments = Assignment::all();
return view('assignments.index', ['assignments'=>$assignments]);
}
...
Here's the (beginning of) the Assignment.php model:
namespace App;
use Carbon\Carbon;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Database\Eloquent\Model;
class Assignment extends Model
{
use FormAccessible;
protected $fillable = ['person_id', 'task_id', 'dueDate', 'status', 'completedDate'];
public function person()
{
return $this->hasOne('App/Person');
}
...
The database table for "assignments" has a person_id column, as a foreign key to the "people" table.
If I remove person->name from index.blade.php, leaving the line as <td>{{$assignment}}</td>, the page loads fine but of course, shows the object. So, it seems to have something to do with accessing the Person associated with the Assignment.
Any ideas about what is causing the error?
I guess this issue because the name of class is wrong App/Person should be App\Person
and you can write it like the following:
public function person()
{
return $this->hasOne(\App\Person::class);
}
There is a minor mistake in your model:
public function person()
{
return $this->hasOne('App/Person');
}
Change the above code to below code:
public function person()
{
return $this->hasOne('App\Person');
}
it is better if you use the below code:
public function person()
{
return $this->hasOne(Person::class);
}
Person::class is same as App\Person.