Laravel 5 - using dynamic properties in view - php

I have a dynamic property user in my model:
class Training extends Model
{
...
public function user()
{
return $this->belongsTo('App\User');
}
}
And I can easy get username in controller like this:
Training::find(1)->user->name
But I don't know how to perform the same in view. I tried this:
Controller:
return view('training/single', Training::find(1));
View:
{{ $user->name }};
but without success, I'm getting error Undefined variable: user. So it's look like I can't access dynamic property in view.
Any idea how can I use dynamic property in views?

I fear that's not really possible. There's no way to set the $this context in your view to the model. You could convert the model into an array with toArray() but that would include the related model and you would have to access it with $user['name'].
I personally would just declare the user variable explicitly:
$training = Training::find(1);
return view('training/single', ['training' => $training, 'user' => $training->user]);

Use eager loading
return view('training/single', Training::with('user')->find(1));

Related

Failure to extract data from a relationship with laravel

I am trying to make a one-to-many relationship, but I get the following error
Undefined property: stdClass::$client (View:
C:\wamp\www\intranet\resources\views\users\list.blade.php)
The problem is that I am working with an existing database that in the tables does not have id fields, and the foreign keys would also be the typical ones like client_id
My model Client.php
class Client extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmundfunc';
public function employee(){
return $this->hasMany('App\Employee');
}
}
My model Employee.php
class Employee extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmtrabajador';
public function client(){
return $this->belongsTo('App\Client', 'COD_UND');
}
}
In nmtrabajador COD_UND field would be the foreign key that relates to nmundfunc.
And I try to get the data out like this: {{$user->client->CEN_DESCRI}}.
but it does not throw me the error, how can I solve it?
My Controller where I send in sight
public function index(){
$users = DB::connection('dpnmwin')->table('nmtrabajador')->where('CONDICION', '=', 'A')->get();
return view('users.list',array(
'users' => $users
));
}
You have to call basis on relations.
This code will return you data.
If you have id then you can find by id like below
$employee=Employee::find(1);
Or if you want to fetch all data then you can call all method.
Employee::all();
And then you can just get it by relation as you define in models.
$client=$employee->client->CEN_DESCRI;
Retrieving data from the instance is based on the methods which we have use.
Here in this answer, you can get that
Property [title] does not exist on this collection instance
I hope it will work.
If table doesn't have 'id' as primary key you should specify what the primary key is inside your model:
protected $primaryKey = 'your_primary_key';
Relation looks good, after that you must make sure $user is a defined instance of Employee, because your error probably means that your instance wasn't even defined, so for example if you are using list.blade.php, you need to change the return of your controller and indicate that you want to pass data to your view, for example you could do it like this:
return view('users.list', compact('user'));
Where user is an instance of Employee saved on '$user'
Update
First you should check your user is retrieved properly, you can check it by placing a dd($user)
And when you return a view you can pass information to it, a cleaner way of doing what you are trying to do is what I wrote earlier so you would end up having something like this:
public function index()
{
$users = DB::table('nmtrabajador')
->where('CONDICION', '=', 'A')
->get();
// dd($user) for debugging you are retrieving the user properly
return view('users.list', compact($users));
}

Laravel get record from database in blade view

I would like to known how to get data from database in blade like from User table:
{{ Auth::user()->name }}
I have table user_settings
I would like to get record from this table by logged user id like this:
{{ UserSettings::user()->my_field }}
How can I do that?
Try this on your blade view
{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }}
In default, model file is inside App folder.
Such direct access to database table is not preferred though, you can return this as a variable from controller function like,
$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;
return view('view_name',comapact('field'));
and use in blade like
{{$field}}
Another good way is posted by Orkhan in another answer using eloquent relationship.
Hope you understand.
You need to retrieve the UserSettings associated to the authenticated user:
UserSettings::where('user_id', Auth::id())->first()->my_field
You can defined a method named current() to return that for you.
class UserSettings extends Model
{
public static function current()
{
return UserSettings::where('user_id', Auth::id())->first()
}
}
Then use:
UserSettings::current()
On the other had it would better to use one-to-one relationship on user model:
class User extends Model
{
public function settings()
{
return $this->hasOne('App\UserSettings');
}
}
Then use:
Auth::user()->settings->my_field

Custom model method to get a relation in Laravel

I try to define a custom Model method in Laravel. I have a n:m relation between Subscription and Notification over SubscriptionNotification.
I already defined the default relations:
public function subscription_notifications() {
return $this->hasMany('App\SubscriptionNotification');
}
public function notifications() {
return $this->belongsToMany('App\Notification', 'subscription_notifications');
}
Now I want to define a method, which returns a collection of notifications. I collect the IDs of the notifications I want in an array and write the following method:
public function notifications_due() {
// Collect $notification_ids
return $this->belongsToMany('App\Notification', 'subscription_notifications')->whereIn('notifications.id', $notification_ids)->get();
}
But when I want to use the mothod by $subscription->notifications_due, I get the following error:
[LogicException]
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
I'm new to Laravel (I come from Rails). I don't know if this is in Laravel even possible. Maybe someone can help me. Thanks!
Remove the ->get() part in the method notifications_due. get() will return a Collection, but when calling the method as a property (or magic method), Laravel expects the method to return an instance of Relation. Laravel will then execute the query and transform it to a Collection automatically.
Also, you can use your already defined notifications() method:
public function notifications_due() {
// Collect $notification_ids
return $this->notifications()->whereIn('id', $notification_ids);
}
Remove the get call from your relationship method, for example:
public function notifications_due() {
return $this->belongsToMany(
'App\Notification',
'subscription_notifications
')->whereIn('notifications.id', $notification_ids);
}
Use it just same:
// It'll return a collection
$dues = $subscription->notifications_due;
To get all the ids from the collection you may try this:
$ids = $dues->pluck('id');
Also, you may add more constraints if you want if you use it like:the
$dues = $subscription->notifications_due()->where('some', 'thing')->get();
Or paginate:
$dues = $subscription->notifications_due()->where('some', 'thing')->paginate(10);

Laravel 5 model object retrieval

I am new to Laravel 5 and was wondering how model object retrieval works.
For instance I have a separate table that is referenced by another table and I want to get the records from that.
Item Table
Category Table
I was trying to extend the User model
Class Item extends Model {
public function getCategory(){
$category = Category::find($this->category_id);
return $category;
}
}
So when I try to access the object retrieved in my view,
{{ $item->getCategory()->name }}
I get the error
Undefined property: Illuminate\Database\Eloquent\Builder::$name
What am I doing wrong? And what is the best practice in doing this? I used to do this in Symfony and it works so I was wondering how its done in Laravel.
Any help and input would be greatly appreciated.
Thank you all.
As stated in the docs here's how I did it
Class Item extends Model {
public function category()
{
return $this->hasOne('App\Category', 'id', 'category_id');
}
}
And accessed the object in the view this way
{{ $item->category->name }}

Laravel Relationships can't access

I have 3 models: User, A, B and C.
User.php
public function a()
{
return $this->belongsTo('App\A');
}
A.php
public function b(){
return $this->belongsTo('App\B');
}
B.php
public function cRelation(){
return $this->hasOne('App\C');
}
Then, i execute my query and load the relationship
$tests = User::all();
$tests->load('a.b.cRelation');
Now, in my view file, if i print this:
#foreach($tests as $test)
{{$test->a->b}}
#endforeach
I can see my c_relation magic property as expected.
But if i try to access it nothing is printed.
Where am i wrong? Why if i print the parent object ($test->a->b), i can see the property but i can't print it?
Here's what's happening...
When you just print a model in your template with {{ $test->a->b }}, the model is converted into JSON to make the output more readable.
When converting a model to JSON, Eloquent by default changes the relationship names from camelCase to snake_case.
However when you access a relationship from the model, you always use the method name so in that case {{ $test->a->b->cRelation }}

Categories