Where do I put "extra" default fields for a Laravel model? - laravel

This question is about the "correct" design pattern, not about functional code. I want to adhere to best-practices and use the right feature in Laravel.
I have a model called Order which contains users' product orders.
Order has several columns, like which product, quantity, etc, and is stored in mysql, with a belongsTo() call to the User model.
When I place an order using the OrderController, I call an outside API that I set up using a Service class.
Here's the main part of the question:
I need to add certain fields that the API requires, but on my end are always the same, so it would make sense to me to pack these into an object of their own and just append that object to the end of my Order data before submission.
So where is the "Best" place to put this extra data? In my model? In a Service class? I'm leaning toward the service class, but that just doesn't feel right.

You have an action that gives a single or a collection of a model. So the best practice for adding some extra data to those results is using JsonResource and ResourceCollection. By using them you can easily add anything you want in the ToArray method.
Lumen doesn't have Illuminate\Http by default but you can add it to your project.
Official Http package of laravel
Eloquent: API Resources Documentation.

Related

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.

Laravel - Updating DB in Controller vs Model

I have a model that I require to update, such as User. In a large application, this User will also have relationships, and updating it would be more than a mere User::find($id)->update(Input::all()).
Should the updating be performed in the Controller, or be a method within the User model itself?
I always thought that I should put it in the model, since it is model specific. But I've seen most people perform the task in the controller. What is the reasoning for this?
As said in the pattern names, the controllers control any model query or update. Based on this, the controller will be responsible for fetching, changing and saving the model.
If some actions are to be reused in many controllers, acting on a set of models, they would go in a "repository".
In your example, you are using Input::all() to hydrate your model, which you definitely have to change. Any user value has to be checked and/or sanitized. I would also recommend against using all and prefer either get or post, so you set up a minimal restriction.
So, I definitely let the controller be responsible for the "glue", having repositories for any collection matter, services and hydrators to change the object, and the model itself staying for only getters and setters, managing their own data in their own scope.

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

Auto completes in codeigniter

I have lots of auto completes like City, country, companies, brands, people names, etc. Now my team is currently giving each autocomplete a separate model in codeigniter. The issue i have is then each autocomplete has its own code. I want to make it templatized so there is only 1 code base for all auto completes and it pulls the autocompletes in and out dynamic.
Is it possible or is the way my team is doing it the correct way?
Your CI models should be organized to reflect your domain, so in the case of cities, countries, companies and such, each are different entities and deserve a seperate model. More files does not mean it is less maintainable.
As for autosuggest, your model simply needs to deliver the data to a controller that will be called using Ajax. You can do the json_encoding of the data stream in the model or the controller, I prefer to use the controller.
So eventually yoiu hopefully have a single autosuggest plugin in the front-end that simply calls different controller URLs. These controllers know which model to use to get the autosuggest data.
This is a clean seperation of duties, and maintainable.

MVC - Sanitizing data, where?

I'm using CakePHP but it's a question about the MVC pattern. I have in my form the input-text for the tags (separated by commas). To add the tags I've created a Tag model method that basically check if the tag exists and then add the new tag or just a new unit in the tag counter (the Tag model has these fields: id, name, slug, count).
In the controller I explode the tags field and pass one tag at a time.
The question is: where do I sanitize data? In the controller or in the model method? I think it should be in the controller because that's where I explode but in term of reusability I think I should sanitize data in the model.
What do you think?
You should sanitize your data on the View for client-side and Controller for the server-side.
I would say that, strictly speaking, sanitizing your data should occur in the controller, but sanitizing also generally refers to cleaning user input to avoid many issues, such as SQL injection. Since you're using the term "sanitize" in a different context, we have to pay more attention to what that context is.
You're not cleaning up user input, which means it doesn't really need to happen in the controller. You're changing the result of this action depending on whether or not the item you're saving already exists in the database. Therefore, in my mind, it should be happening in the model (or, as MunkiPhD specified, have a method in some sort of helper class that you can call from anywhere - but I say call it in the model).
Edit: Usually, in MVC, the model knows whether it's supposed to save a new row into the database or update an existing one based on whether or not your model instance has a valid ID. If it has an ID, the model should save to the row indexed by that ID. If it does not, the model creates a new one. It's my understanding that all you want to do is know where to make it decide whether to create a new one or update an existing one, and that happens in the model.
I disagree with sanitizing the data for storage in controller, and think the best place is to do it in model, as controller should not know how the data is stored, but sanitizing needs that knowledge (e.g. mysql_real_escape_string() for storing a MySql vs. pg_escape_string() for PostgresQL, or maybe checking for valid XML if stored in an XML file, or something else for different storage mechanisms).
To prevent things like cross site scripting, do not sanitize the data before storing, as you may have some legitimate use for some html tags later on, and do that (ideally) in view or in controller.
You'd want to sanitize it in from your controller, however, "from" doesn't mean "in." Have a separate class sanitize the data - that way you can call that class from wherever you need to.
You basically want to create the contract that your model will receive good data all the time, which means you'd have to sanitize it beforehand.

Resources