Laravel add custom method for all eloquent models - laravel

I am looking for a way to add few custom methods which will be used in all models. I can imagine 3 ways of doing it :
Adding custom method to main Eloquent's Model.php class file(I want to avoid doing this as this is a core file)
Creating a custom model class with required custom methods, which will extend to eloquent's Model class and all the models in the project will extend to custom model class.
Adding a trait which will have my methods and include it inside all models
However, I want to do it more efficiently and best way possible. Is their any other way to do it?
PS I am using laravel 5.2 as its an old project.

Based on the comment discussion and adding my experience in Laravel I would suggest you to go either with #2 or #3 approach as #ceejayoz have specified in the comments
first one is definitely a bad approach as you need to modify the core which is not at all a good practice. Second and third are both good approaches.
But, before that you need to check your requirements if literally all models (including any future ones your app will ever have) need the extra functionality, however you can use traits for all models.
If I have the choice probably I will go for traits over custom models as traits are relatively simple then custom models

Related

Laravel Eloquent - Trait vs Observer

Lets say I have some models with the field "slug". On model saving, I want to set the slug automatically.
My first guess to do this, was to create an observer and reacting on the "creating" event. But after a short google search, I found https://github.com/spatie/laravel-sluggable
Why do they prefer Traits over Observers? When to use Traits , when should I use Observers?
Observers are nothing new but classes in Laravel Framework
You may use observers to group all of your listeners into a single class. Observers classes have method names which reflect the Eloquent events you wish to listen for
But Trais are for reusing codes
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
You use the package's trait in model and it does all the slugging-mechanism
The package of Spatie you linked uses traits to implement the code to your model, they listen to the events [here] just like you would do in an observer.
So they do it to make it easy to implement these features, via the trait.

is it better to have different controller and different model in MVC

I'm new at the MVC model. Im still learning on how to use codeigniter framework.
So, i have some questions, is it better to have different controller and different model to perform some functions or is it better to combine all into one controller and one model?
Thanks.
It is all up to you. But consideration seems like having particular controller for one object like User or Article etc. Depending on controller you would like to have appropriate model for manipulating consisting data User_model.php or Article_m.php.
If you have some generic methods and code that you want to pull out from DB from many controllers, you might have something like Generic_m.php.
If you have some other functions related to some area you can make your own library and use those.
For simple functions that don'e belong to any specific set you can create your own helpers.

Can i use instances of a laravel model instead of facades?

I'm wondering whether it is possible/advisable to use instances of a laravel model instead of using the Facade. Why all this trouble? I have a model which will be used with many tables, and i want to be setting the model's table automatically using the constructor. Is it possible/advisable, or what is the best approach of achieving the same end?
I have researched around with no much success.
UPDATE
THis is the scenario: an exam system, where different exams are "created". after an exam is created, a table is created in the database under the name Exam_#, where # is the ID of the exam. I want to access all exam from one model: Exam, but you see the particular table the model is to use can vary significantly, so we cannot set the table variable statically. The model shall not know the table it will use until it(the model) is called. So thats why i was wondering whether i can be passing the ID of the exam when i am calling the model or something like that. I hope my question is now more clear.
At the end of this, Laravel is still PHP... Anything you can do in PHP can be done in Laravel.
is (it) possible/advisable to use instances of a laravel model instead of using the Facade?
You can achieve exactly the same results using an instance of the model as you would using the static facade.
$user = User::find(1);
$user2 = new User();
$user2 = $user2->find(1);
Both instances of the above model contain the same results.
Is it advisable? I really don't like the static facades at all, they bring with them more trouble than they are worth, especially when it comes to testing (despite being able to mock them, they create tight coupling where most of us need loose coupling). My answer to this would be: don't use the facades at all.
What is the best approach of achieving the same end?
As #JoelHinz suggested, create a base model with common properties and then use the models as they are intended. i.e. ONE table to ONE model and create the relationships between them. Don't use the same model for multiple tables, this is not how Laravel models were intended and you will lose a lot of the power Eloquent provides by taking the approach you mentioned.
Updates from comments
To get you started with testing in Laravel this is a good end to end tutorial Tutsplus Laravel4 + Backbone. Ignore the backbone part, what you're interested in is the testing parts that start about a 1/3rd of the way down the page. This will get you testing controllers straight away and introduce you to the repository pattern to create testable DAL structures.
Once you get the hang of writing tests, it becomes very easy to write a unit test for anything. It may seem like a scary subject, but that is purely down to not understanding how it works, it really is quite simple. Take a look at the PHPUnit documentation as well, it is an excellent resource.

Joomla how can i create model from other component

I'm a beginner in joomla. I create own component and would like to use model from other component (exactly contentbuilder).
I find few different ways how to create model but my problem is that
class ContentbuilderModelEdit extends JModel
use JPATH_COMPONENT_ADMINISTRATOR in it. When i create model ContentbuilderModelEdit i get warnings in lines that using JPATH_COMPONENT_ADMINISTRATOR constant.
Is it possible to create model using that constant from other component?
Thanks for your answers
Alas no. The JPATH_COMPONENT and JPATH_COMPONENT_ADMINISTRATOR are defined constants, and cannot be changed.
Sometimes the developers do this instinctively (it's easy) without realizing the kind of limitation they're putting on other developers. You might consider contacting the developers and propose such a change; if they accept, you won; if they don't, write a sed script that performs the changes (replacing it with JPATH_SITE and JPATH_ADMINISTRATOR . '/components/com_contentbuilder', and apply it after each update.
Or, copy their model into your component and rename it if it supports it.
:)
To call a model from another component you need firstly to include the path of this model:
JModelLegacy::addIncludePath(JPATH_SITE . '/components/comp1/models', 'Comp1Model');
Secondly you have to create an instance of your model:
$model = JModelLegacy::getInstance('Model1', 'Comp1Model');
After that you should be able to use the methods of your model.
ref link

Best practices for implementing models in the MVC pattern

What are the best practices for implementing models in the MVC pattern. Specifically, if I have "Users" do I need to implement 2 classes. One to manage all the users and one to manage a single user. So something like "Users" and "User"?
I'm writing a Zend Framework app in php but this is more a general question.
The model should be driven by the needs of the problem. So if you need to handle multiple users, then a class representing a collection of Users might be appropriate, yes. However, if you don't need it, don't write it! You may find that a simple array of User objects is sufficient for your purposes.
That's going to be application and MVC implementation specific. You might well define a class collecting logically related classes, or you could define a static register on the user class. This is more of an OO question than MVC.
I'll second Giraffe by saying the use of included collections is almost always better than trying to write your own.
But I think your original question could be reworded a little differently... "Do I need a separate class to manage users other than the User class?
I use a static factory class to build all of my users and save them back to the database again. I'm of the opinion that your model classes need to be as dumbed down as possible and that you use heavy controller classes to do all of the work to the model classes.

Resources