Astrotomic Translatable - pivot column - Laravel 9 - laravel

I'm having trouble translating a pivot column.
I've been trying all day to add this translation but it still doesn't work.
I'm using the package: https://github.com/Astrotomic/laravel-translatable
Plain tables work fine, but pivot doesn't.
My code (the naming was quick, as the code will work, I'm going to refactor it):
class Offer extends Model implements TranslatableContract
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
'description'
];
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class, 'attribute_offer')->using(AttributeOffer::class)->withTimestamps();
}
class Attribute extends Model implements TranslatableContract
{
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
];
public function values(): BelongsToMany
{
return $this->belongsToMany(Offer::class, 'attribute_offer', 'attribute_id', 'offer_id')->using(AttributeOffer::class);
}
class AttributeOffer extends Pivot implements TranslatableContract
{
use Translatable;
public $incrementing = true;
public array $translatedAttributes = [
'content',
];
protected $fillable = [
'attribute_id',
'offer_id',
];
}
class AttributeOfferTranslation extends Model
{
protected $table = 'attribute_offer_translations';
public $timestamps = false;
protected $fillable = [
'content',
];
}
class OfferController extends Controller
{
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $slug => $values) {
$pivot = $offer->attributes()->whereSlug($slug)->first()->pivot;
foreach ($values as $locale => $value) {
$pivot->translate($locale)->content = $value;
}
}
}
The structure of the attributes is:
[
'test' =>[
'en' => 'test',
'es' => 'test',
'de' => 'test',
],
'test2' =>[
'en'=> 'test',
'es'=> 'test',
'de' => 'test',
],
]
Unfortunately pivot->translate() always returns null.
Also, when I manually add transactions to the database, it does not display it.
I will be very grateful for help with this translation.

Okay, I fixed it like this, only I have to pass id instead of slugs.
class Offer extends Model implements TranslatableContract
{
...
public function attributeValues(): HasMany
{
return $this->hasMany(AttributeOffer::class);
}
}
class AttributeOffer extends Pivot implements TranslatableContract
{
...
protected $translationForeignKey = 'attribute_offer_id';
...
}
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $id => $values) {
$offer->attributeValues()->whereAttributeId($id)->first()->update($values);
}
}

Related

Relationship between pivot tables - return resource do not found using pivot or belongsToMany

good afternoon!
I would like some help from them regarding the scenario below:
I have 3 tables, 1 is the Moviment which is the main one, the 2 is the cart_moviments which is the secondary one which when I enter the movement data, it saves some data in cart_moviments and I have the 3 table called vehicles, which I have all the vehicle information, all of them have a foreignId, just to relate them.
So on my return from the resource, I have Moviment->cartMoviment, and I want to access it from cartMoviment ->vehicles, which I can't, because it doesn't relate.
My code Store:
public function store(StoreMovimentRequest $request, StoreCartMovimentRequest $requestCart, StoreDocumentRequest $requestDocument)
{
$this->authorize('create', Moviment::class);
$moviment = Moviment::create($request->validated());
$moviment->cartMoviment()->create($request->validated());
foreach(array($request['key_number']) as $notasFiscais) {
foreach($notasFiscais as $notas) {
$moviment->document()->create($notas);
}
}
return new MovimentResource($moviment);
}
My CartMoviment MOdel:
class CartMoviment extends Model
{
use HasApiTokens, HasFactory, Notifiable, UserTenant;
protected $fillable = ['type', 'vehicle_cart_id'];
// protected $table = 'cart_moviments';
public function Moviment() {
return $this->belongsTo(Moviment::class);
}
public function Vehicle() {
return $this->belongsTo(Vehicle::class, 'vehicle_cart_id');
}
My Moviment Model:
class Moviment extends Model
{
use HasApiTokens, HasFactory, Notifiable, UserTenant;
protected $fillable = [
'document_type_id', 'people_id', 'company_id', 'vehicle_id', 'department_id'
];
public function Vehicle() {
return $this->belongsTo(Vehicle::class);
}
public function cartMoviment() {
return $this->belongsToMany(Moviment::class, cartMoviment::class);
}
`
My resource Array:
public function toArray($request)
{
return [
'id' => $this->id,
// 'count' => $this->count(),
'type' => $this->type,
'department_id' => $this->department_id,
'person_id' => $this->people_id,
'person_name' => $this->person->name,
'vehicle_id' => $this->vehicle_id,
'vehicle_board' => $this->vehicle->board,
'vehicle_status' => $this->vehicle->status,
'vehicle_manufacturer' => $this->vehicle->vehicleModel->name,
'vehicle_type' => $this->vehicle->vehicleType->type,
'cart_moviment' => $this->cartMoviment,
My return resource
"cart_moviment": [
],
"documents": [
],
`
I need relationship , thanks you very match.

Is it possible to add an object structure under an array to the Eloquent model scheme?

I got a JSON object like this:
{
"campaignDesignerAccountId":0,
"remoteAccountId":0,
"month":5,
"usage":[
{
"service":"affectivity",
"type":"renderVideo",
"taskCount":"59",
"totalDuration":"2597.845625400543"
},
{
"service":"creatives",
"type":"HTMLToPDF",
"taskCount":"248",
"totalDuration":"5412.990473032003"
},
{
"service":"creatives",
"type":"pdf",
"taskCount":"229",
"totalDuration":"27953.42511272434"
},
{
"service":"displayads",
"type":"html5",
"taskCount":"8",
"totalDuration":"199.255334138869"
}
]
}
I want to add the object under the usage array as an eloquent model schema.
For example:
protected $fillable = [
'campaignDesignerAccountId',
'remoteAccountId',
'[usage].service',
'[usage].type',
'[usage].taskCount',
'[usage].totalDuration',
'month',
];
Is it possible?
Currently, my eloquent model looks like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PublishEngineMonthlyLogs extends Model
{
protected $fillable = [
'campaignDesignerAccountId',
'remoteAccountId',
'usage',
'month'
];
protected $casts = [
'usage' => 'array'
];
// Sorting parameters
protected $allowedSorts = [
'month'
];
// Permission of filtering fields with texts
protected $allowedFilters = [
'month',
'campaignDesignerAccountId'
];
}
I fixed the problem by using mutators.
I updated my model class like this:
class PublishEngineMonthlyLogs extends Model
{
protected $fillable = [
'campaignDesignerAccountId',
'remoteAccountId',
'usage',
'month',
'year'
];
protected $casts = [
'usage' => 'array'
];
// Sorting parameters
protected $allowedSorts = [
'month'
];
// Permission of filtering fields with texts
protected $allowedFilters = [
'month',
'campaignDesignerAccountId'
];
public function setServiceAttribute($value)
{
$this->attributes['service'] = $value;
}
public function setTaskCountAttribute($value)
{
$this->attributes['taskCount'] = $value;
}
public function setTotalDurationAttribute($value)
{
$this->attributes['totalDuration'] = $value;
}
public function setTypeAttribute($value)
{
$this->attributes['type'] = $value;
}
}
And assigned values like this:
$tableData= [];
$log= new PublishEngineMonthlyLogs;
$log->setAttribute('service', $dataRow['service']);
$log->setAttribute('type', $dataRow['type']);
$log->setAttribute('taskCount', $dataRow['taskCount']);
$log->setAttribute('totalDuration', $dataRow['totalDuration']);
array_push($tableData, $log);

incorrect table name inserting into using Laravel Excel to Collection

I'm attemptng to insert relational data using the Laravel Excel concern ToCollection
use Maatwebsite\Excel\Concerns\ToCollection;
however the query is attempting to insert into the table objective_years and not objective_year
ObjectivesImport.php
namespace App\Imports;
use App\Models\Objective;
use App\Models\ObjectiveYear;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
class ObjectivesImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$objectiveDetail = Objective::create([
'description' => $row[0],
'guidance' => $row[1],
'team_id' => $row[2],
'subject_id' => $row[3],
]);
$yearDetail = ObjectiveYear::create([
'objective_id' => $row[4],
'year_id' => $row[5],
]);
}
}
}
I have two models with a many to many relatinship pivot.
Objective
class Objective extends Model
{
use HasFactory;
protected $fillable = [
'description', 'guidance','subject_id','team_id'
];
public function years ()
{
return $this->belongsToMany('App\Models\Year');
}
}
Year
class Year extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
public function objectives()
{
return $this->belongsToMany('App\Models\Objective')->withTimestamps();
}
}
ObjectiveYear
class ObjectiveYear extends Model
{
use HasFactory;
protected $fillable = [
'objective_id', 'year_id'
];
}
Controller
class ImportController extends Controller
{
public function getImport()
{
return view('import');
}
public function import()
{
Excel::import(new ObjectivesImport, request()->file('csv_file'));
return redirect('/')->with('success', 'All good!');
}
}

Search in Laravel relation using json column

I have problem with search in json column.
I have 3 relations:
products
feature products
feature_values
My tables:
products: https://ibb.co/1dgjT6m
feature products: https://ibb.co/K9f74Wn
feature_values: https://ibb.co/rc3zG5W
My migrations:
Product:
class Product extends Model implements Presentable
{
....
public function featureProducts()
{
return $this->hasMany(FeatureProduct::class, 'product_id');
//return $this->belongsToMany(Feature::class, 'feature_product', 'id');
}
}
FeatureProduct
class FeatureProduct extends Model
{
protected $table = "feature_product";
protected $with = [
'values'
];
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
}
FeatureValues:
class FeatureValue extends Model
{
use SoftDeletes,
Translatable;
protected $fillable = [
'feature_id',
'value'
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
protected $translatable = [
'value'
];
public function feature(): BelongsTo
{
return $this->belongsTo(Feature::class);
}
public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
{
return new FeatureValueUrlPresenter($this);
}
}
I need to show products with features and assigned features_values
I heve problem with search in json column: feature_product. feature_values_ids
When I have INT in this column, then this is working fine:
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
When I have:
["1", "2","3"]
I haven't any results :(
Haw can I repair it?

How to create seeding hierarchy in laravel

I have problem creating a seeding hierarchy in Laravel, is there way i can achieve hierarchy by just creating a seeding data. I have 3 column [Vehicle,Model,Variant] so each vehicle has different model and variant. I will show you the sample table that I created on excel that I wanted to achieve.
Expected Output:
Here is my seeding function:
<?php
use Illuminate\Database\Seeder;
use App\Variant;
use App\Vehicle;
use App\VehicleModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CarsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
foreach (Vehicle::all() as $vehicle_data) {
foreach (VehicleModel::all() as $vehicle_model_data) {
foreach (Variant::all() as $variants_data) {
DB::table('cars')->insert([
[
'make' => $vehicle_data->name,
'model_id' => $vehicle_model_data->id,
'variant_id' => $variants_data->id,
'created_at'=>date('Y-m-d H:i:s'),
'updated_at'=>date('Y-m-d H:i:s')
]
]);
}
}
}
}
}
Car Model:
class Car extends Model
{
//
protected $table = 'cars';
protected $fillable = [
'id',
'make',
'variant_id',
'model_id'
];
public function variants() {
return $this->hasMany('App\Variant','id','variant_id');
}
public function models() {
return $this->hasMany('App\VehicleModel','id','model_id');
}
}
Variant Model:
class Variant extends Model
{
//
protected $table = 'variants';
protected $fillable = [
'name'
];
}
Vehicle Model:
class Vehicle extends Model
{
//
protected $table = 'vehicles';
protected $fillable = [
'name'
];
}
Vehicle Model:
class VehicleModel extends Model
{
//
protected $table = 'vehicle_models';
protected $fillable = [
'name'
];
}
Assuming the following relations
Vehicle hasMany VehicleModel(s)
VehicleModel hasMany Variant(s)
class Vehicle extends Model
{
public function vehicle_models()
{
return $this->hasMany(VehicleModel::class);
}
}
class VehicleModel extends Model
{
public function variants()
{
return $this->hasMany(Variant::class);
}
}
Try this
public function run()
{
$vehicles = Vehicle::with('vehicle_models.variants')->get();
foreach($vehicles as $vehicle) {
foreach($vehicle->vehicle_models as $model) {
foreach($model->variants as $variant){
Car::create([
'make' => $vehicle->name,
'model_id' => $model->id,
'variant_id' => $variant->id
]);
}
}
}
}

Resources