Laravel change stored value of polymorphic relationship - laravel

I am trying to make the stored value of a polymorphic relationship more readable by other applications. Currently the polymorphic model type is stored as the FQCN of the model. Using the example in the Laravel Docs, imageable_type could be "App\Product", or "App\Staff". However, this value can be a little more difficult to manage if any non-laravel applications which aren't based on this convention and are also accessing the same database. Also, if the model FQCN ever gets refactored, you have to modify your other applications to account for the change.
Is there a way to change the type to something more consistent and readable, and then have a mapping class that maps the keys to the model? (e.g. have "product" map to "App\Product")

Yes. This is a change that was recently implemented.
Add this to your service provider (in the boot method):
Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'product' => App\Product::class
]);
If you simply pass an array of model names, it'll default to using the table names:
Illuminate\Database\Eloquent\Relations\Relation::morphMap([
App\Product::class,
App\Staff::class,
]);

if you are adding morphMap method to service provider, you might want to use
'product' => \App\Product::class
( "\" before App),otherwise your namespace can be wrong.

Related

DDD Laravel. Repository pattern. How to retrieve an object from persistency and convert it into a not Laravel Entity model?

I'm aplying DDD in Laravel.
In this architecture, the entity (conformed by the corresponding value objects) is not a Laravel Model extended class (because the domain layer needs to be agnostic to the infrastructure)
So... when I retrieve some data inside the repository implementation, the result is a stdclass object, and I need to return it as the entity object.
Anybody knows the best approach to do this?
Thanks!
To get this, I tried to convert from stdclass to entity by manual, but it's look hacky and dirty.
Ok, got it.
I found two different approaches, just in case others are fighting with the same problem.
Option 1: Embracing the Eloquent Active Record.
Inside the infrastructure layer, I created a Eloquent model to represent the Entity, and I use it as a vehicule for eloquent queries. Like this, all the conection with the framework stay contained in the infrastructure, without polluting other layers.
Option 2: Apply Doctrine in Laravel.
Doctrine has a package for laravel. Doctrine, as occurs in Synfony, is using data mapping, so no worries with that.
Thanks anyway!

get laravel eloquent model relationships

is there any way to get the defined relationships in eloquent model. I have a situation where I need to get the model relationships so I can update all other eloquent models that relies on a specific id before delete it
There's no unified method to iterate over all registered relationships of a class. You can, however, access all the currently loaded relationships of a model instance (via the ->relations attribute or the getRelations() method), but that's not what you're up to. I'd suggest you take a look at laravel's documentation on inserting and updating relationships. So far that's the best laravel provides out of the box, the rest is developing approaches.
Try this function:
public function getRelations()
You can use
$model->getRelations()
function to get all relations
Also refer below link for details https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_getRelations

Laravel Dynamic Eager Loading for Dynamic Relationships

Laravel Version: 5.5
PHP Version: 7+
Database Driver & Version: mysql 5.7+
Scenario:
I have a SaaS application that has flexible database structure, so its fields are bound to change, especially given it has a Json field (for any extra database structure to be created from client side of the application), including relationship based fields. so Account Table can have dynamically created employee_id field, and thus the need to access relationships dynamically
Problem:
I need to EagerLoad models based on this dynamic relationship. If I had something like this:
// Account Model
public function employee(){
return $this->belongsTo(App\Employee);
}
it would be easy. But what I have is this:
public function modelBelongsTo(){
return $this->belongsTo($dynamicClassName, $dynamicForeignKey);
}
Now if I eager load this, I'll get Account Model instance with related Employee on key modelBelongsTo. This is how Eloquent Names based on the function of eagerload. But after this I cannot use this function again to eagerload a second model because it'll just overwrite results on modelBelongsTo key.
Possible Solution Directions:
1) Can I Somehow change laravel's process to use a name I provide?
or
2) Can I write functions on the fly to overcome this so I'll write employee function on the fly?
or
3) Worst Case Scenario: I iterate over all records to rename their keys individually because I am using a pagination, it wouldn't that big of a deal to loop over 10 records.
Us a morph relationship
define the various dynamic classnames say
Employee
Boss
Morph works by having the related key and the table name stored in the parent table, it means to relate them you have to use a join or an orm and you cant have foreign key constraint on it as it links to different tables.
then have your account have morphs where
we have
Account
as top class
then we have
EmployeeAccount, BossAccount
which have their relation to boss and employee
then in Account have morphto relation call it specificAccount()
to which in its child morphs have the morph relation to Account
then add it to $with so to eager load them so when fetching account you could simply do
$account ->specificAccount
to get its morph child. which is nullable
This is totally dynamic such that if you have other classes in future you can just add and add the morph relationship. This may be applied to any reflection or runtime evaluated and loaded classes/code though it is not advisable to do this, as you can always edit code to create new functionality without affecting previous.

Can eloquent ignore irrelevant data in Laravel 4

I have a form that accepts data which will be used to create two new database table entries. The form takes both the users details and their address. The user details will be stored using the User::create(Input::all()) method into the users table, and the address details will be stored using the Address::create(Input::all()) method into the addresses table of the database.
The issue I'm currently having is that Eloquent is complaining that street, city, country etc do not exist on the users table. This is true, that data is to be used for the address side of things.
Is there any way to have eloquent ignore irrelevant data in the Input::all() array when it's passed to the create methods?
P.s. I'm aware that mass-assignment isn't a good idea, I'm only using it here to simplify my question.
Sure enough you can use $fillable array in your model to declare fields allowed for mass-assignment. I believe this is the most sufficient solution in your case.
class User extends Eloquent {
protected $fillable = [
'first_name',
'last_name',
'email'
];
}
Have you tried looking at Input::only('field1','field2',...);, or even Input::except('field3')? They should be able to accomplish what you are looking for.
Source: http://laravel.com/docs/requests
You'll have to unguard that model using these http://laravel.com/docs/eloquent#mass-assignment and then manually unset those values before you execute save(). I highly recommend using a form object or something similar to complete this kind of service for you outside of your model since it's safer and usually clearer to intended behavior.
#cheelahim is correct, When passing an array to Model::create(), all extra values that aren't in Model::fillable will be ignored.
I would however, STRONGLY RECOMMEND that you do not pass Input::all() to a model. You really should be validating and verifying the data before throwing it into a model.

Why can't i use functions like ->addAttributeToSort('name', 'ASC'); in my custom model?

I had created a custom model which uses ORM, i tried out "Weblog" example in the link http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-5-magento-models-and-orm-basics and i was able to retrieve values from db using collection, but i cannot use functions like "->addAttributeToSort('name', 'ASC');" with my collection object.
Are these functions specific only to product model such as "catalog/product"? if so how could i use such filtering capabilities to my custom function?
Thank you very much..!!
Those functions are specific to EAV models. Otherwise you are limited to the 'field' equivalents like addFieldToFilter() and addOrder().
To make your custom model use an EAV resource read the rest of that tutorial, especially part 7.
you can use functionally of setOrder('$attribute','ASC')
to reorder

Resources