I'm the beginner of laravel 5.4. I just want to ask. I want to display in Assignments table the Collectors but it doesn't show.
Screenshot of the Assignments Index
Code in my Assignment index.blade.php
<td>{{ $assignment->collector['firstname'] }} {{ $assignment->collector['lastname'] }}</td>
Assignment.php model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector.php model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
AssignmentsController
public function index()
{
$assignments = Assignment::all();
return view('assignments.index', compact('assignments'));
}
I search to how to display the collectors with both many to many relationship. I read the doc about using pivot but I had still errors about that. Can you help me resolving this? Thanks
$collector is an object, not an array. Use -> syntax to access properties on individual collector models:
$collector->firstname
Since the relationship is many to many you need two loops:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->firstname }} {{ $collector->lastname }}</td>
#endforeach
#endforeach
If you find you often need two fields together, like first and last names, you can create an accessor on the Collector model to easily join them:
public function getFullNameAttribute()
{
return $this->getAttribute('firstname') . ' ' . $this->getAttribute('lastname');
}
Allowing you to then do:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->fullname }}</td>
#endforeach
#endforeach
I'm trying to display authors.where some books have one author and some books have 2 authors. How to manipulate this scenario
here is my html code
#foreach($books as $book)
<tr>
#if (json_encode($book['author']) !== 1 )
<td>{{{ json_decode(json_encode($book['author'][0]),true) }}} &
{{{ json_decode(json_encode($book['author'][1]),true) }}}</td>
#else
<td>{{{ $book['author'][0] }}}</td>
#endif
</tr>
But It is displaying only 2 authors but not single author.Any help or suggestions that would be appericated
Thanks In advance
I don't know how you have your tables setup but if authors are on a separate table as they should with a hasMany relation you should do this(assuming your relations are well formed)
Book Model, you described a One to Many relation between Books and Authors so you should use something like this:
public function authors()
{
return $this->hasMany('App\Author');
}
#foreach ($books as $book) :
#foreach($book->authors as $author) :
// do whatever you wish with all the authors here
#endforeach
#endforeach
I'm trying to echo out the name of the user in my article and I'm getting the
ErrorException: Trying to get property of non-object
My code:
Models
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('App\User');
}
protected $table = 'news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Schema
table users
table news
Controller
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
Blade
{{ $article->postedBy->name }}
When I try to remove the name in the blade {{ $article->postedBy }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field namein my table and aUser` model. Am I missing something?
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:
First, as suggested by Jimmy Zoto, my code in blade
from
$article->poster->name
to
$article->poster['name']
Next is to add a second parameter in my belongsTo,
from
return $this->belongsTo('App\User');
to
return $this->belongsTo('App\User', 'user_id');
in which user_id is my foreign key in the news table.
If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.
For example: In a table, you may want to list users with their roles.
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->role->name }}</td>
</tr>
#endforeach
</table>
In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
</tr>
#endforeach
</table>
Edit:
You can use Laravel's the optional method to avoid errors (more information). For example:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ optional($user->role)->name }}</td>
</tr>
#endforeach
</table>
If you are using PHP 8, you can use the null safe operator:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user?->name }}</td>
<td>{{ $user?->role?->name }}</td>
</tr>
#endforeach
</table>
I implemented a hasOne relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.
REASON WHY THIS HAPPENS (EXPLANATION)
suppose we have 2 tables users and subscription.
1 user has 1 subscription
IN USER MODEL, we have
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case.
we cannot use arrow function further after subscription like below
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
if($user->subscription){
return $user->subscription->abc;
}
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
I had also this problem. Add code like below in the related controller (e.g. UserController)
$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);
Laravel optional() Helper is comes to solve this problem.
Try this helper so that if any key have not value then it not return error
foreach ($sample_arr as $key => $value) {
$sample_data[] = array(
'client_phone' =>optional($users)->phone
);
}
print_r($sample_data);
Worked for me:
{{ !empty($user->role) ? $user->role->name:'' }}
In my case the problem was in wrong column's naming:
In model Product I've tried to access category relationship instance to get it's name, but both column name and relationship had the same name:
category
instead of:
category_id - for column name
category - for relationship
Setting up key name in relationship definition like
public function category():hasOne
{
return $this->hasOne(Category::class,'category');
}
didn't help because as soon as Laravel found property named category gave up on looking for relationship etc.
Solution was to either:
change property name (in model and database) or
change relationship name (Eg. productCategory )
It wasn't an error in my case. However, this happened to me when I was trying to open users.index, because while testing I've deleted some data from the 'STUDENTS' table and in the 'USERS' table, a foreign key ('student_id') represents the 'STUDENTS' table. So, now when the system tries to access the 'USERS' table in which foreign key ('student_id') is null since the value got deleted from the 'STUDENTS' table.
After checking for hours when I realise this, I insert the same data again in the 'STUDENTS' table and this resolved the issue.
I have two tables
One QUESTIONS_TITLES entry has many QUESTIONS entries. The titles contain a group of questions.
QUESTIONS
id | question | ... | question_titles_id
QUESTIONS_TITLES
id | title
MODEL QUESTION
class Question extends \Eloquent {
public function questionTitle() {
return $this->belongsTo('QuestionsTitle', 'question_titles_id');
}
}
MODEL QUESTION
class QuestionsTitle extends \Eloquent {
protected $fillable = ['title', 'question_cat_id', 'type'];
protected $table = 'questions_titles';
public function question() {
return $this->hasMany('Question');
}
}
in my question controller i do:
$questions = Question::all();
$this->layout->content = View::make('questions.index', compact('questions'));
in my view i want a group of questions with the corresponding parent title
#foreach ($questions as $question)
<tr>
<td>{{ $question->questionTitle()->first()->title }}</td>
<td>{{ $question->id }}</td>
<td>{{ $question->question }}</td>
</tr>
#endforeach
this works. but why do i need first()? it doesn't look clean
when i drop it i get
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$title (View: /vagrant/app/views/questions/index.blade.php)
$question->questionTitle() returns a BelongsTo object, not the QuestionTitle object. When you call $question->questionTitle()->first() you're executing the first() method on the relationship. This through laravel magic is getting you the correct answer. Though what you should really be doing is: $question->questionTitle->title. When you access the questionTitle attribute Laravel automatically resolves the relationship for you.
I have "posts" table that has many-to-one relationship with "categories" table. The goal is to show all of posts and their categories.
Tables:
Posts: id, content, category_id, etc
Categories: id,name
Here's my code
Models:
class Posts extends Eloquent
{
public static $table = 'posts';
public function categories()
{
return $this->belongs_to('Categories');
}
}
class Categories extends Eloquent
{
public static $table = 'categories';
public function posts()
{
return $this->has_many('posts');
}
}
My controller
public function get_posts()
{
$posts = Posts::with('categories')->all();
return View::make('admin.posts')
->with('title', 'Posts')
->with('posts', $posts);
}
My view
#foreach($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->categories->name }}</td>
<td><small> {{$post->updated_at}} </small></td>
<td>
<button>
{{HTML::link_to_route('edit_post','Edit',array($post->id))}}
</button>
{{Form::open('admin/delete','Delete')}}
{{Form::hidden('id', $post->id)}}
<input type="submit" name="edit_post" value="Delete"/>
{{Form::close()}}
</td>
</tr>
#endforeach
ERROR:
Error rendering view: [admin.posts]
Trying to get property of non-object
I am a newbie, please help me solve this issues
{{ $post->categories->name }} before test is categories exists
Example:
#if( ! empty($post->categories))
<td>{{ $post->categories->name }}</td>
#else
#end if
Aesis.
Just use ::all() instead of ::with(..)->all()
categories is an array as you are using a has_many relationship. There are many categories, hence an array is returned, so to access it you have to index it like an array
the correct solution would be
$post->categories[0]->name
Are you using Laravel 4? First the syntax for declaring relationship is hasMany and belongsTo, in camel case. Check it out in Laravel documentation
In view, check if categories are empty collection, ie., whether post has its category:
#if($post->categories->count())
<td>{{ $post->categories->name }}</td>
...
#endif
By the way, I would use singular form as model class name, like Post and Category instead of plural forms. And in Post class I would define inverse one-to-many relationship with singular form, to show there's only one entry in category table for this given Post.
public function category()
{
return $this->belongsTo('Category');
}