Laravel Controllers - laravel

I have a page for creating a driver and adding his cars - drivers/create. A driver must have at least one car.
So I keep all the logic of storing the driver info in DriverController#store, but I also need to save cars info. I feel it is not a correct way to store elements of a Car class in the DriverController.
What would be a correct (or just a better) way in my case?

You can create a public static store method in CarController, and then invoke the method in DriverController#store.
Or create a car in CarModule and invoke it in DriverController#store.

If you're using Eloquent ORM, Laracasts has a free video series on v5.4 from scratch.
Two of the videos show you one way to set up a one-to-many relationship, but using a blog with comments. You could follow their example but substitute blog with driver, and comments with cars.
Laravel 5.4 From Scratch: Eloquent Relationships and Comments
https://laracasts.com/series/laravel-from-scratch-2017/episodes/15
Laravel 5.4 From Scratch: Add Comments
https://laracasts.com/series/laravel-from-scratch-2017/episodes/16
There's also a lot of other ways to approach the problem, with the Repositories or Service Layers, but those can lead you down a rabbit hole.

Related

Laravel Eloquent Relationships methods syntax

everyone:
I'm trying to create an application with several many to many relations, including a m-m rel onto the same model. It's a headache. In the official docs there is no so much information. I've been looking the code for belongsToMany method, in HasRelationShips.php, but there are not description on the parameters use.
Where can I get detailed documentation about the use of the parameters, in order to learn the right way to create any kind of relationships?
Do you know any book or document which details the working of all of the methods and parameters, so I can read it and REALLY learn how do they work?
Thanks everyone
Bro, in the DOCs you can find it easily.
Belongs to Many is like that:
public function companys(){
return $this->belongsToMany('App\Users', 'companys_users', 'user_id', 'company_id')->withTimestamps();
}
https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

Eloquent: API Resources vs Fractal

Quick question, what is the difference between Eloquent: API Resources and Fractal?
To me, it looks like the same thing?
Both are used to transform API json responses to standardise the response structure.
However, API resources is inbuilt in Laravel and it's very easy to use. Fractal was the preferred way to go when API resources were not in-build in Laravel. Fractal has some methods which make it little extensive as compared to API resources.
But if you consider the core functionality, both are same with different syntactical sugar.
Most of the things which were in fractal, you can do natively in Laravel now. Plus API resources eliminate the need of any extra installation and setup. The nomenclature is very easy in API resources to start with
both of them are created for one job but their solutions are different in many ways.
Relationships:
in fractal you can easily add related models to the response. also, you can control when the related models should be presented in the response . (default include vs Available include)
for example your client can use ?include=rate to get the rate model from an article when needed! consider that, the fractal will eager load your relationships when you forgot to load it.
in API Resources you have no control over relationships and you should decide to have relationship or not in the first place. otherwise, if you forgot to eager load data for it, it will cost you too many queries to load related model (1+n problem).
Serializer
in basic usage of api resource you have no control on how data will map to final response.
for example if you want jsonnapi specification for your responses, you should manage all of the works by yourself. but in fractal you have it in the first place.
as a conclusion
i recommend you to use fractal in this case. (or use dingo package for api but consider complexity of dingo !!)

Laravel add custom method for all eloquent models

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

Should I save related models in repository?

I am working with Laravel for almost two years and trying to understand all the benefits of using Repositories and DDD. I still struggle with how to use best practices for working with data and models for better code reusability and nicer Architecture.
I have seen other developers suggesting to generate models in factories and then use Repositories for saving these models like :
public function add(User $user)
{
return $user->save();
}
but what should I do, in case my user model has models related with it, like images, description and settings.
Should I create repository for each model and call ->add() function 4 times in the controller or should I place the saving logic inside the UserRepository ->add() function passing all models as well as user? Also, how about update function, that logic might also be quite complicated.
Update - what I need is a practical example with realization.
It's always difficult to deal with "right way" questions. But here is one way.
From a DDD perspective, in this specific context, treat the User object as an aggregate root entity and the other objects as child value objects.
$description = new UserDescripton('Some description');
$image1 = new UserImage('head_shot','headshot.jpg');
$image2 = new UserImage('full_body','fullbody.jpg');
$user = new User('The Name',$description,[$image1,$image2]);
$userRepository->persist($user);
First thing to note is that you if really want to try and apply some of the ddd concepts then it is important to think in terms of domain models without worrying about how to persist them. If you find that you are basically writing a CRUD app with a bunch of getters and setters and almost no business logic then pretty much forget about it. All you will end up doing is to add complexity without much value.
The persist line is where the user will get stored. And you certainly don't want to have to write a bunch of code to store and update the children. Likewise, it would normally be waste of effort to make repositories for value objects. If you are going this route then you really need some sort of database layer that understands individual objects as well as their relations. It is the relations that are the key.
I assume you are using Laravel's Eloquent active record persistence layer. I'm not familiar enough with it to know how easy it is to persist and update an aggregate root.
The code I showed is actually based more on Doctrine 2 Object Relation Mapper and pretty much works out of the box. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/ It is easy enough to integrate it with Laravel.
But even Doctrine 2 is largely CRUD oriented. In different domain contexts, the user object will be treated differently. It can start to get a bit involved to basically have different user implementations for different contexts. So make sure that the payoff in the domain layer is worth the effort.
I am not a PHP guy but from what I can find, Laravel an MVC framework, which has nothing to do with DDD.
Check this presentation, it does not to go to domain modelling, more concentrating on tactics but at least it has some goodness like command handling and domain events, briefly explains repositories with active record.
It also has references to two iconic DDD books at the last slide, I suggest you have a look at those too.

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.

Resources