How to catch model events in pivot tables - laravel

I want to track (record) the changes made to each database row. This means, saving a log of each action (insert, update, delete) made to each record of each table.
This issue is solved for models, as they extend from a BaseModel and I'm using model events. However, I cannot seem to find a way to record the changed from pivot tables.
Given the following tables users, profiles and profile_user(profile_id, user_id), I have the following code:
class User extends BaseModel {
public function profiles() {
return $this->belongsToMany('Profile');
}
}
class Profile extends BaseModel {
public function users() {
return $this->belongsToMany('User');
}
}
abstract class BaseModel extends Model {
public static function boot() {
parent::boot();
static::created(function($model) {
return LogTracker::saveRowCreatedOrUpdated($model, true);
});
static::updated(function($model) {
return LogTracker::saveRowCreatedOrUpdated($model, false);
});
static::deleted(function($model) {
return LogTracker::saveRowDeleted($model);
});
}
}
This allows me to record the changes from user and profile but not from profile_user.
I've tried to create a ProfileUser model that extends from Pivot (Illuminate\Database\Eloquent\Relations\Pivot) where I defined the model events but that didn't work.
I'm guessing that's because I never create a new instance of this model. So, I've added the following to my User model (and similar code to Profile):
class User extends BaseModel {
// (...)
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
if ($parent instanceof Profile) {
return new ProfileUser($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
// (...)
}
Still, the events are never fired (actually this method is never executed).
I am updating the relationship through sync():
$user->profiles()->sync(explode(',', $values["profiles"]));
I'm looking for a solution that doesn't involve firing a custom event (as this means that I would have to do this for each pivot table in database).
How can I use model events in pivot tables?

I am aware you don't want a custom event situation but I cannot find any non-custom solution.
You can however do a very simple custom one (pretty much pulled right from Laravel docs):
DB::listen(function($sql, $bindings, $time)
{
//regex matching for tables in SQL query
//as well as firing your event handling code
});
http://laravel.com/docs/4.2/database#running-queries

Related

Laravel many to many relationship with pivot

I'm using Laravel Filament.
I got a projects and responsibles tables in a many-to-many relationship. But also another table of responsabilityTypes
projects
id
title
responsibles
id
name
responsabilityTypes
id
name
project_responsible
project_id
responsible_id
responsibilityType_id
And here are my relationships setup:
Responsible.php
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType_id')
->withTimestamps()
->using(AcademicoProyecto::class);
}
Project.php
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType_id','sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
I have set up a class for the pivot table like so:
ProjectResponsible.php
use Illuminate\Database\Eloquent\Relations\Pivot;
class AcademicoProyecto extends Pivot
{
}
ResponsibilityType.php
//Don't know how to set up
My question is, when the user is in a Project Edit page and clicks on the "attach" button, in order to add a Responsible record, a Modal pops up to select a Responsible, but I also implemented a Select list to display the different types of responsibilities.
What am I missing to set up in order to access and display the types of responsibilities in the select list and attach it to the pivot table?
Your question asks about "access and display" but you have no controller or view code. But for the model, it's just a simple relationship between two tables, so define it as such:
class AcademicoProyecto extends Pivot
{
use SoftDeletes;
public function responsibilityType() {
return $this->belongsTo(ResponsibilityType::class);
}
}
class ResponsibilityType extends Model
{
protected $fillable = ["name"];
}
Now you simply update the other models to access the relationship in the withPivot() call.
class Responsible extends Model {
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
class Project extends Model {
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType', 'sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
Now you should be able to do, for example:
$foo = Responsible::with("projects")->first();
foreach ($foo->projects as $project) {
echo $project->pivot->responsibilityType?->name;
}

How to disable loading of relationships when not needed in Laravel

is it possible to disable the loading of relationships, but only in some cases?
Here are my models:
class League extends Model
{
...
public function country()
{
return $this->belongsTo(Country::class)->with('translations');
}
}
class Country extends Model
{
...
public function translations()
{
return $this->hasMany(CountryTranslation::class, 'country_id');
}
}
class CountryTranslation extends Model
{
...
}
In many places, I need to load the translations relationship for Country, but on some pages, I want to display information about the League and its Country only. There I don't want to show the CountryTranslation collection.
Here is the code for that page:
$country = $league->country;
Is it possible only for this line to disable the relations?
So, you're currently finding out one of the reasons for not defining the eager loading inside of the relationship. The first suggestion would be to remove the with() from the relationship definition, and add it in where needed. If desired, you can create another relationship that has the eager loading enabled, and it can use the base relationship to keep it DRY:
public function country()
{
return $this->belongsTo(Country::class);
}
public function countryWithTranslations()
{
return $this->country()->with('translations');
}
If this code change is not feasible, you will need to change how you're accessing the country relationship. When you access the relationship attribute, it lazy loads the relationship, and you don't have the ability to modify the relationship query. So, instead of accessing the relationship attribute, you'd need to call the relationship query so you can modify it.
Therefore, you won't be able to do $country = $league->country;, but you can do:
$country = $league->country()->without('translations')->first();
he with() simply eager loads the translations to avoid additional queries, but you should be able to load the translations with and without it, without with( adds additional queries. https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
You will want to change:
public function country()
{
return $this->belongsTo(Country::class)->with('translations');
}
to
public function country()
{
return $this->belongsTo(Country::class);
}
If you want to load translations, you can do it in the controllers
// if you want translations at some point do this:
$league = League::with('country.translations')
$country = $league->country->translations
// if you do not want translations
$league = League::with('country')
$country = $league->country;
If you do not want to touch:
public function country()
{
return $this->belongsTo(Country::class)->with('translations');
}
you can create another method
public function countryClean()
{
return $this->belongsTo(Country::class);
}
$country = $league->countryClean;

Storing Data and at the same time updating data on a different table in Laravel 8

I have two tables, 'vehicles' and 'assign_vehicles'. Whenever I assign a vehicle to a driver, I want the 'status' column on the 'vehicles' table to be updated to 'assigned'. How do I go about it?
There is some assumptions to be made. You will have to have classes that looks similar to this.
public class Vechicle extends Model {
public function assigned()
{
return $this->hasMany(AssignVehicle::class);
}
}
public class AssignVehicle {
public function vehicle()
{
return $this->belongsTo(Vehicle::class);
}
}
You can monitor the AssignVehicle event and add it to your boot method. Add it in AssignVehicle.php class. From there access the vehicle and update the status. Note there is a creating and created event, creating is before saving to the database and created is after saving to the database
public static function boot() {
parent::boot();
static::created(function (AssignVehicle $assignVehicle) {
$assignVehicle->vehicle->status = 'assigned';
$assignVehicle->vehicle->save();
});
}
For this to trigger remember to use standard Laravel approaches for events to trigger. The following will work.
AssignVehicle::create([
'vehicle_id' => $vehicle->id,
// your fields
])

How can I get all records belonging to the model class as relation on a 1-M polymorphic relation

I am trying to store statuses of multiple models in a polymorphic relationship and use them from there.
The retrieving of the status works but besides that I need to get all (available) the statuses belonging to that specific model. And then eager load them so I can use them in a select form or somewhere else.
Here is a representation:
// Status.php
class Status extends Model
{
public function statusable()
{
return $this->morphTo();
}
}
// Article.php
class Article extends Model
{
public function status()
{
return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
}
}
// Post.php
class Post extends Model
{
public function status()
{
return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
}
}
Here I can get the status(details) of the selected model like App\Article::first()->status()->get() or eager load it as expected. What I want is to add a method where I can call (all) statuses that belong to that particular model. For example:
$article = App\Article::first()->statuses();
and then return all available statuses to this model. I can (did) of course create a method like:
// Article.php
...
public function statuses()
{
$statuses = Status::where('statusable_type', self::class)->get();
return $statuses;
}
But this way I cant eager load it because I don't return a relationship. So is there a cleaner way where I can use eager loading as well?

Returning counts of a relationship model in Laravel

I have a model for user and annotations along with a pivot table user_like for storing annotations liked by user. The annotation table is also associated with another model (ranges) through hasMany relationship. I am trying to return all annotations along with its user, ranges and total number of likes.
The code below works for user, ranges and even likes. But, I am only interested in returning the count of likes and not the actual values (i.e. list of users liking the annotation). Is there a way to include just the counts for one of the models from the relations?
Eloquent query:
$annotations = Annotation::with('ranges')
->with('likes')
->with('author')
->where('document_id', $docid)->get()->toArray();
The model:
class Annotation extends Eloquent {
public function ranges()
{
return $this->hasMany('Range');
}
public function author()
{
return $this->belongsTo('User', 'user_id');
}
public function likes()
{
return $this->belongsToMany('User', 'annotation_like');
}
public function countOfLikes()
{
return $this->likes()->count();
}
}
If you want to retrieve count for multiple annotations using eager loading then you need the following 'helper' relation setup:
public function countLikesRelation()
{
return $this->belongsTo('User','annonation_like')->selectRaw('annotation_like, count(*) as count')->groupBy('annotation_like');
}
// then you can access it as such:
$annotations= Annotation::with('countLikesRelation')->get();
$annotations->first()->countLikesRelation->count;
// to make it easier, we create an accessor to the count attribute
public function getLikesCountAttribute()
{
return $this->countLikesRelation->count;
}
//And then, simply use
$annotations->first()->sectionsCount;

Resources