Problem in showing additional field of pivot table in Larvel Nova - laravel

I am using Laravel Nova for my admin side.
I have this problem that in my pivot table, I added additional field.
I have user table and event table. User can have many event, and event can have many users. So I created a pivot table for the 2 models. But I want to the status of the event of user. So I added additional field for status in pivot table.
My problem now is in the Laravel Nova.
In my event resource, I have this:
BelongsToMany::make('Pending Users', 'pendingUsers', 'App\Nova\User'),
It shows another table for pending clients. I can already get the list of users in specific event but I can't show to the table the status of the event of user. If the user is approved or still pending.
What strategy is best in my case? I am thinking to make a model for Event and User.
I don't know how to show the additional field of pivot table in BelongsToMany in Laravel Nova. It just shows what I added in User Resource of Nova. Like ID and name. But I don't know where the status of user's event will show. I want to show it in the table of BelongsToMany of events to users.

You need to make sure that you're defining the relationship in BOTH models, and then letting Nova know which fields you want to show like this:
In your event resource:
BelongsToMany::make('Users')
->fields(function() {
return [
Text::make('status')
];
}),
In your event model:
public function users()
{
return $this->belongsToMany(User::class)->withPivot('status');
}
In your user model:
public function events()
{
return $this->belongsToMany(Event::class)->withPivot('status');
}

I got this working by defining ->withPivot('filed name)' on the relationship it drove me insane for a long time.
BelongsToMany::make('your_relationship')
->fields(function () {
return [
Text::make('your_text'),
];
})
Your relation will be here something just like this what i said previous
public function users()
{
return $this->belongsToMany(User::class)->withPivot('filed name');
}

Related

Laravel nova and belongsToThrough?

Is there a way to display in Laravel Nova Resource a relation like this ?
$report->meter->user
where
- a report belongs to a meter
- a meter belongs to a user
I am in report ressource and I want to display related user
I struggled with this lately. What we seek is a BelongsToThrough relationship field. That type of relationship isn't natively supported by Laravel, which means there's no field for it in Nova either. However, you can easily implement it in Laravel by installing this package: https://github.com/staudenmeir/belongs-to-through
You can then add your report relationship to the User model.
// App\Models\Report
use \Znck\Eloquent\Traits\BelongsToThrough;
public function report()
{
return $this->belongsToThrough('App\Models\User','App\Models\Meter');
}
And you can use a regular BelongsTo relationship within Nova.
// App\Nova\Report
public function fields(Request $request)
{
return [
BelongsTo::make('User')
]
}
Note: This would work for the Report index/details views, but you'll want to exclude it from the edit form. (Consider a computed Text field, if you want to display the user on the edit form.)

Laravel Relationships Guidance

Could anyone please tell me how to create a relation between 3 tables.I have 3 tables. User, Profile and Post. Now I want to list all posts on the home page with user name form users table and profile image from the profiles table and posts from posts table.
There are few things to consider before suggesting any code. Your database structure, eloquent model classes and any other condition you want to apply before getting posts from database.
Hope, your profiles and posts table (both) contains user_id field.
You have to define two relationships.
In Post model define:
public function user() {
return $this->belongsTo('App\User');
}
In User model define:
public function profile() {
return $this->hasOne('App\Profile');
}
Now, before forwarding your $posts to view you may run this statement:
$posts->load('user.profile);
This will load relevant user and their profile within posts. Like this:
posts:[
{...,
user:{
...,
profile:{...}
}
},
...
]
Further reading recommended:
Belongs To Relationships
Nested Eager Loading

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

Laravel nova overriding/setting custom value for the Fields or Has Through relationship

I am developing a Web application using Laravel. For the admin panel, I am using Laravel Nova. What I am trying to do now is that I need to use data from the table which has relationship through another table. To be, clear, see my database structure below.
items
=====
id
name
price
sub_category_id
sub_categories
==============
id
name
parent_category_id
parent_categories
=================
id
name
What I am trying to achieve inside the Nova is that I want to display the parent category name of the item on the item index/list page. The first thing is that I do not want to create custom attribute something like this in the model
protected $appends = [
'parent_category_name'
];
function getParentCategoryNameAttribute()
{
//code here
}
Therefore, there are two solutions I can think of. The first solution is using the HasThrough relationship. But I cannot find it in Nova. So, I cannot use it. The second solution is that overriding the field value on render. Something like this.
Text::make("fieldname")->fillUsing(function($request, $model, $attribute, $requestAttribute) {
//$model->sub_category->parent_category - then I can return a value
return "Parent category name";
})->onlyOnIndex()
But the above code is not working. So, what would be the best approach to handle the has-through relationship in Nova?
Assuming you have defined the relationship sub_category & parent_category properly.
Define the relationship in Item model as below
public function parent_category()
{
return $this->sub_category->parent_category();
}
Then use it in Item resource as below.
BelongsTo::make('Parent Category')
->hideWhenCreating()
->hideWhenUpdating(),

Laravel model events for attach/detach

I have 3 tables, products, taxonomies and product_taxonomy, as you can tell the 3rd table is a pivoting table. In taxonomies table, I hold a field called num_products which keeps track of the quantity of products that belongs to this taxonomy. Now how can I trigger a model event every time a product is attached to or detached from a taxonomy? I want to update that num_products value in the model event.
Laravel models have events that you can hook into. You have the following options:
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored
You'd code it like this:
User::creating(function($user)
{
if ( ! $user->isValid()) return false;
});
Docs: http://laravel.com/docs/4.2/eloquent#model-events
Or you could use Model Observers that are baked in. You have the following options:
creating
updating
saving
You would write a method on your model:
class UserObserver {
public function saving($model)
{
//
}
public function saved($model)
{
//
}
}
You can then register then register the observer:
User::observe(new UserObserver);
Docs: http://laravel.com/docs/4.2/eloquent#model-observers
Hope it helps.

Resources