Laravel 5.5 eloquent one-to-many not work using get() - php

I have one to many relationships and need to show using where conditions.
When I use findOrFail() it's working as well.
$foo = Model::findOrFail(1);
on my template blade
#foreach($foo->bars as $index=>$bar)
{{ $bar->name }}
#endforeach
on my code above, it's working. but the reference to an id, that's not what I need.
I need it using where conditions. like this:
$foo = Model::where('conditon', 1)->get();
then I call it on my blade template with
#foreach($foo->bars as $index=>$bar)
{{ $bar->name }}
#endforeach
then I get an error:
ErrorException (E_ERROR) Property [bars] does not exist on this collection instance.
It seems after get() I cannot call child with $foo->bars
How do you get this to work?

The findOrFail() method returns an instance of the "Model".
The get() method returns a collection of instances of the "Model" even if there is only one result.
if you want just one result, use first() instead of get().
$foo = Model::where('conditon', 1)->first();
then in the blade template do
#if($foo)
#foreach($foo->bars as $index=>$bar)
{{ $bar->name }}
#endforeach
#endif
if you need multiple results, do another foreach().
#foreach($foo as $oneFoo)
#foreach($oneFoo->bars as $index=>$bar)
{{ $bar->name }}
#endforeach
#endforeach
if you are going with the "multiple" solution, i suggest you name your variable "foos".
$foos = Model::where('conditon', 1)->get();
and so
#foreach($foos as $foo)
#foreach($foo->bars as $index=>$bar)
{{ $bar->name }}
#endforeach
#endforeach

Try to use ->first() instead of ->get().

Because ->get() retrieve multiple results which fit the query criteria.
You can either loop through $foo results or use ->first() to retreive the first query match.

Related

Laravel how to take from another table?

I have a table called "logs" with custom column "auth_id" and i have another table called "users" with same column name "auth_id" and column "username".
How can i take it from "logs" with "logs.auth_id" and get username by "users" table?
Now i'm getting results by:
$match->messages = DB::table('logs')->where('match_id', '=', $match->match_id)->get();
Blade:
#foreach ($match->messages as $message)
{{ $message->auth_id }}:
{{ $message->message }}
Example: Now i'm getting AUTH5556 with {{ $message->auth_id }} but i need to get USERNAME from "users" table by {{ $message->auth_id }}
Don't use joins, this is the whole reason for using something like laravel (eloquent). You need to define a relationship between your models.
On your user model you would define a method
public function logs()
{
return $this->hasMany(Log::class);
}
On your log model
public function user()
{
return $this->belongsTo(User::class);
}
Now you need to make sure on your logs table you have a user_id column.
Now you can simply get the log for example
$log = Log::find($id);
And you can retrieve any information about the user who owns that log, for an example in a blade file.
{{ $log->user->username }}
To get reverse information you need to iterate through the results as the user can have many logs. Eg:
$user = User::find($id);
Then you'd do something like this in your blade
#foreach($user->logs as $log)
{{ $log->column_on_log_you_want }}
#endforeach
You also need to look into eager loading.
This is what makes laravel so clean and nice to use.
Read through the documentation
You need to use JOIN in your query to get username from users table. Here is the link to Laravel manual

LARAVEL 5.3, Get User Name and Role Name (Using Laravel Model Relationships)

Testgrammatical or spelling errors
► clarify meaning without changing it
► correct minor mistakes
► add related resources or links
► always respect the original author
Get the data using eager loading:
$user = User::where('id', $userId)->with('roles')->first();
Then display the data:
{{-- Display full name --}}
{{ $user->first_name.' '.$user->last_name }}
{{-- Display all role names of the user --}}
#foreach ($user->roles as $role)
{{ $role->name }}
#endforeach
I guess relation here is many to many, so you need to change roles() relation to belongsToMany()
If you're using some package with many to many relationship, but you're only attach one role for user, you can display role name with this:
{{ $user->roles->first()->name }}
Also, you could use accessor to get full name:
public function getFullNameAttribute($value)
{
return $this->first_name.' '.$this->last_name;
}
To display full name using accessor:
{{ $user->full_name }}
#foreach($users as $user)
{{$user->name}} {{$user->roles->first()->name}}
#endforeach

How to get Carbon instance from collection variable in Laravel 5.1

there does any one know how to change collection variable into Corban diffForHumans instance... e.g.
{!! $item['date']->diffForHumans() !!}
it gives an error of Call to a member function diffForHumans() on string
You could just create the object on the fly with Carbon::parse():
{{ Carbon::parse($item['date'])->diffForHumans() }}

Laravel Blade how to use if statement for null or empty

In the Blade templating engine, how to use "if" to determine null or empty?
{{{ Auth::user()->age }}}
You can do it as bellow
#if (empty(Auth::user()->age))
// your if code
#else
// your else code
#endif
you can also use:
{{ Auth::user()->age or 'Age not provided' }}
so you will have more clean blade template
This works for me:
{ Auth::user()->age ?: 'Age not provided' }}
Summarizing Jorge and Razi's answers, cleanest way to do it is this:
{{ Auth::user()->age ?? 'Age not provided' }}
also this:
{{ Auth::user()->age ?: 'Age not provided' }}
but this one doesn't work (I'm on Laravel 8, this only works with lower Laravel versions):
{{ Auth::user()->age or 'Age not provided' }}
If you try this last method, it returns 1 instead of what you want.
Also check this question: Check if variable exist in laravel's blade directive
In my case, as I was using HeidiSQL as a DB Manager, I had to guarantee that the column field was really NULL. To do that, I clicked on the field with the right mouse button, clicked on "Insert value", then on "NULL". (It's the same as Shift+Ctrl+N). In the beginning, I was just entering NULL on the field, which is a String I guess, so it was always "truthy", not NULL. Doing that solved the problem for me, even writing {{ Auth::user()->age }}.

Laravel 4.2 - Accessing object properties

I'm having a bit of an issue trying to access all of a objects properties.
In my UsersController:
public function edit($id)
{
return View::make('users.edit')->with('user', User::find($id));
}
In users/edit view I can access only some of the objects properties such as {{ $user->username }} and {{ $user->email }} however, I cannot access {{ $user->id }} or {{ $user->role_id }} ... the app complains about trying to get the property of a non-object. On the other hand if I use {{ dd($user->id) }} it returns the correct value as expected. Being new to Laravel and Eloquent I'm at a loss for why this might be.
Any help is appreciated.
Try change variable name user to something else. Some frameworks has $user variable reserved in they templating system.
It turns that I inadvertently overwrote the $user object which resulted in having access to only some of the object attributes. The non-object error made sense considering the second $user was no long the user object returned from the controller. It was a silly mistake and I feel foolish for overlooking it in the first place. Thank you everyone for the input!

Categories