Laravel 4.2 force mass assignment on createOrUpdate and similar methods? - validation

I've been working on an API for awhile now that has a sort of 'soft' api validation so I can use Backbone more easily on the front end. Basically the design principal has always been to only validate and update the attributes sent back that we care about. On the backend, I use the model's fillable array to limit this after validating the input array. This way we don't have to annoy people when they accidentally send back model data that we don't allow them to touch as the docs clearly state whats fillable. People seem to enjoy working with the API.
What we run into is a problem because we want to use things like 'createOrUpdate' for our backend stuff that's creating or updating models automatically. Basically we end up adding things to fillable that go against our user facing input validation. Trudging around the docs I came across 'forceFill' and other various 'force' methods, but noticed that they are missing from the more magical methods like 'createOrUpdate'. Seems like they should be methods, or at least boolean flags that can be passed to the methods to force, and maybe these options are built into Laravel 5+?
Before I go ahead and write my own methods in the base, I just wanted to ask if this is already built into 4.2 and I'm just missing it? I also wanted to create this thread as it may be informative to people still confused by how Laravel's mass assignment works.
If I don't get any feedback I'll probably just delete it.

Model::unguard(); is added in 5.1 https://laravel.com/docs/5.1/seeding available in 4.2.
You just call it before you create the object, and then you can fill any fields using createOrUpdate(), firstOrNew(), create() etc.
Correction, here it is in the L4.2 API: https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_unguard
see also: Model::reguard()

Related

Laravel Create Function to be used in different Controllers/in the same Controller

It's more a general question, I want someone to point me to the direction I should go.
1) FUNCTION FOR SAME CONTROLLER: I have two methods: Store and Update in the same controller. They both should contain some complex request validation (which I can't do via validator or form request validation because it's too complex). This means for me now using the same code twice in two methods... How can I take this code, create a function and use it in both Store and Update methods just with a single line, like:
do_this_function($data);
2) FUNCTION FOR DIFF. CONTROLLERS: I have another code which I use in many different Contollers. It transliterates Russian letters into Latin ones ('Сергей' = 'Sergey' and so on). How and where should I register this function to be able using it in different Contollers?
transliterate_this($data);
I have read something about helpers. Should I use them? If you an experienced Laravel develper and say so, I will read everything about them. Or, if you advice something else - I'll read about that.:) I just don't want to spend time reading about something useless or "not right way to-do-it".
Appreciate any help!
1) You could create a form request validation or you could just create a private function that would handle the validation and return the result.
2) You can create a helpers.php file, see here, and you put your translation function inside. Then you can call it from anywhere:
In a controller transliterate_this($data);
In a view {{ transliterate_this($data); }}.
You can do complex validation even inside a FromRequest. You can override the getValidatorInstance for example, or any other method from the base class to plug your validation logic on top of the basic validation rules. Else just consider making an external class to handle that complex validation and inject it in your controllers using Laravel's IoC container.
You should create a facade to provide that feature. Then you can easily use it anywhere (and additionally create a helper method for it if that makes you feel better). Something like Transliterate::toLatin($str)
everyone! Thank you all for great answers. But I have discovered that the problem was that I didn't know anything about Object-Oriented Programming.
(Ans I was working in Laravel:)).
After I took an Object Oriented Bootcamp from Laracasts, I started 'seeing' how Laravel actually works and I know can easily create methods inside classes and use them in other classes.
https://laracasts.com/series/object-oriented-bootcamp-in-php
(of course, you can read something else on OOP, but Jeffrey Way has really outstanding explanation talent!)

Problems with Spring Forms and Validation

I am newer to Spring, previously I've worked in PHP and Python. I am having some issues understanding how Spring forms work and are validated. My understanding thus far is that when you are using the your form is backed by a bean, meaning you must provide a bean to the JSP. You can also use the stand HTML forms but then you have to manually retrieve the request parameters in the controller.
Here is the issue I am having. I have a User bean that is using Hibernate Validator, and I have add, edit pages for users. The issue is I don't want the password field to appear on the Edit page, the password is going to be garbage anyway because its using BCrypt. However when the form is submitted validation fails because it expects the password to be present. There doesn't seem to be anyway to do partial bean implementation using Spring Form.
I would like to use Spring Form if possible because it reduces repetitive validation code, and its always nice to work with objects. My thoughts now are do I create an intermediate object and then translate the data from that to my bean. Seems tedious and can lead to the creation of way to many objects. My other thought is to just using plain old HTML forms and pull the params myself and set the values in the object.
I'm not sure what is the best approach or if I'm even thinking on the right track. Spring Forms and the validation is offers seems great, but seems like it isn't particularly flexible. Like I said I'm new to Spring so I may just be missing something or not understanding.
Another issue I have been wrestling with is having multiple objects needed on a form. Lets say I have a User bean, which has the following Properties.
private Role role;
private Country country;
So I need to pass User, List, and List to my JSP. I can get them to display fine, however if the form validation fails when it returns to that page, I lose my role and country objects, unless I re-add them to the model before returning the view name. Am I missing something here or is that the norm. It's a request object so I guess that makes sense but seems tedious to have to re-add them every time.
My understanding thus far is that when you are using the your form is
backed by a bean, meaning you must provide a bean to the JSP.
I'd say mostly true. The form is backed by a bean, but the Spring JSTL tags know how to get to the bean based on the set modelAttribute. The bean is living in what you would consider "page" scope, unless you add set your model attribute to be in session. Either way, if you are using the Spring JSTL tags, they are going to one or the other place to get it.
You can also use the stand HTML forms but then you have to manually
retrieve the request parameters in the controller.
Not true. You can "simulate" the same thing that the Spring JSTL tags are doing. Understand that JSTL tags are very much like macros. They are simply copying in some pre-determined block of code into the output with some very rudimentary conditional statements. The key bit that Spring MVC needs to wire the Model Attribute on the Controller side is the name and value, which are easy to decipher how those get generated/wired together.
However when the form is submitted validation fails because it expects
the password to be present.
You could create a "DTO" or "Data Transmission Object", which is basically a go-between to take the values from the UI and are converted in the Controller/Service layer to the real Model objects on the backend. Or, if you are lazy like me, put the User in session scope, in which case you don't have to post the value as Spring will take the one out of session and just updated the one or two fields you did post. Don't post the password, Spring wont set the password.
My thoughts now are do I create an intermediate object and then
translate the data from that to my bean.
Yes, this is the DTO I referred to. You only need to do it where you need to.
I'm not sure what is the best approach or if I'm even thinking on the
right track.
There are probably thousands of ways to do anything in coding, some more right or wrong than others. I know some developers who are design-Nazi's and would say you should always do it one way or another, but I am not one of those people. I think as long as you are consistent, and you are not doing something completely boneheaded you are on the right track. My #1 concern with all the code I write is maintainability. I
Don't want to spend 20hrs trying to re-learn what I did 6mo ago, so I tend to choose the simpler option
Hate repeating code, so I tend to choose more module designs
Hate having to spend 20hrs trying to re-learn what I did 6mo ago, so tend to make heavy use of JavaDoc and comments where I find the code is tricky (lots of loops, doing something weird, etc)
Another issue I have been wrestling with is having multiple objects
needed on a form.
There are several ways to deal with this too. I have never used it, but you CAN actually have more than one Model Attribute associated with the same form and Controller handler. I think you use a <spring:bind> tag or something. I have seen samples around, so Google it if you think you need that.
My approach is usually to either put something in session or build a DTO to hold all the things I need. The first I use more for things like lists to drive building the view, for instance if I have a drop down of States coming from a table. I would have a List of the States put into session and just use them from there, that way I only go after them once and done.
I use the DTO approach (some might call it a Form Bean) when I have a complex gaggle of things I need to change all at once, but the things are not necessarily connected directly. Just to point out: You can have nested objects in your model attributes and use them in your Spring JSTL tags. You can also have Collections (List, Set, Map) in your Model Attribute and get to those as well, although Spring doesn't handle nested Collections very well.
Hope that helps.

Laravel 4 Model validation vs Controller validation

It seems like official way to validate models in Laravel 4 is through Validator in Controller? Can somebody point out why is it so?
Wouldn't it make more sense to implement validation in Model?
I prefer the Ardent package for making validation of models as smooth and minimal as possible. To me it makes more sense to have the validation rules in the model as well.
It will return false when $model->save() is called and validation fails, then you can get the error messages through $model->errors()->all() for example.
It does make sense to have validation in the models, but this validation should only be there to make sure you don't save any corrupt data.
The Validator is in the Controller because it's used to handle Input, and generate Output.
If you would do the validation in the Model then you either have to return false, and show the user the most random of error messages about invalid data.
You could also return some kine of array containing all the errors that are generated, but that's something a Model shouldn't do.
Or you could throw an Exception, which is something that should be done when a model tries to consume invalid data, but it kills the application, which is not the wanted solution for a form validator.
When doing the form validation in the Controller, you can do everything you want with the error messages, without changing the purpose of a Model.
And in your model you can do a validation to make sure you didn't make a mistake, which will corrupt your database. Because if this happens the application should shut down.
So to put this in a real answer to your question:
Validation in the model makes sense to avoid corrupt data, but if you want to give feedback to the user about invalid input, it should be in the controller.
I wrestled with this for a while and settled on handling most of my validation in a validation service, based something along the lines of this. I can then have different validation rules based on the context.
As Nico mentions, validation in the model is good to avoid corrupt data, but I prefer thin controllers so I pass the functionality that would sit in controller into the service. This also has the benefit of being able to reuse the validation in different controllers/methods.
Why I prefer In-Model Validation: I've worked with both styles and each have pluses and minuses, but I prefer in-model validation. In our current app I don't see in-controller validation as an option, since we're altering our data in so many places (dedicated forms, inline edit, bulk edit, bulk upload, api, etc). I've never really worked with validation services (though they might be an option) but I personally like to keep logic as close to the model as possible, that way I know another developer won't bypass it. I also don't like adding lots of extra files on top of the MVC and basic Libraries folder because it just seems like more you have to think about organizing properly.
Issues with In-Model Validation: These are some things you need to consider to make In-Model work well. SOME OF THESE ARE ALREADY TAKEN INTO CONSIDERATION BY PLUGINS. I think other frameworks (CakePHP) already deal with these, but Laravel doesn't really.
Values that will be validated but not saved to the db (e.g.,
"accepted_agreement").
Many to many or belongs to many
relationships
Setting conditional defaults (not critical but
might want to think about at the same time)
Various form scenarios - sometimes you might need different validation
depending upon which form submits it. The form reference can be a
purgeable attribute for validation maybe?
How will you get back error messages (all in-model validation plugins handle this for you)
Different validation rulesets. Draft creation vs "real" creation. (Most handle this for you)
Ultimately, for simple applications that don't have lots of ways of interacting with the model, I'd say controller validation may be simpler, other then that I prefer in-model.

Why is session data only available in the controller in CakePHP?

So, I like CakePHP and use it lots. When 2.0 came out, I was pleased to see the AuthComponent be made available throughout your whole application as a static class, which makes lots of things much easier - i.e. you no longer have to pass user data as an argument to model methods.
Recently on a project, I have perceived the need to access methods of the SessionComponent from a Model. Specifically, when a user logs in, some checks are performed to see if the user has a valid subscription to the site. This is all done in the model. If the user no longer has a valid subscription, there are a few reasons why that might be. It seems easiest to return false from the model, and at the same time set a flash message giving the reason for the expired subscription. Rather than return an array something like this:
array('status' => 0, 'message' => 'You\'re not welcome here anymore')
which needs interpreting in the controller.
There are other times I have wanted to deal with sessions in models, but this is the example that came to mind.
So, I'd like to know, am I right in wanting to access the SessionComponent in models? Should I just use $_SESSION directly when I have this need? Or am I doing things wrong - are there better ways to code?
you can always use
CakeSession::read()
anywhere in your application. so also in the model.
see previous posts like Reading a session variable inside a behavior in cakephp 2
but be adviced, that you should try to avoid it if possible.
models are supposed to be as stateless as possible - mixing them with sessions makes that more and more blurry.
According to CakePHP cookbook:
Usage of the $_SESSION is generally avoided in CakePHP, and instead
usage of the Session classes is preferred.
There are several different configurations where you can store session data, f.ex. in the database. So, by using CakeSession changes to session configuration will not affect every place where you access session data.
I would advice not to use SessionComponent from the model. Better pass parameters to the model with necessary data. Take a look at Understanding Model-View-Controller.
Passing session control to the Model violates MVC. You should use the model to make the decisions and the controller to reflect those decisions to the application. In a correct MVC enviroment the Model won't even know you are using sessions much less manipulating it.
Also, using the $_SESSION var violates the framework encapsulation. If you find yourself needing to do that, yes, you went wrong somewhere.
You can write and read data in session in model by using Authcomponent and session
App::uses('AuthComponent', 'Controller/Component');
App::import('Component', 'Session');
and you can write and read data using following functions
CakeSession::write('Auth.User.id', '1');
debug(CakeSession::read());

what is the best structure for a project in codeigniter and how to use it?

I have some weeks since im using CI, but now I've found some problems about the structure of my project, I would like someone to give me some clues because I am kinda stuck, the problem is this:
I have my project MVC, so, I am dividing it into files (each per functionality) for example, there is a file with all the functions corresponding at login, and other with all related at post (it's an example), but now I am on a moment where I need to use login or posting into another part of the project, reading I found out i cannot call a controller from another, I can use the helper but still I will need to use a model, so I have to take that code and paste it into the controller where I'm calling the model and so on (and it's not good), I found out I can use modules, still I don't want to go over them until someone could give me an experience of this, i wouldnt like to change the project, is any way I could run all those controllers (i know i can use run:: I'm not sure if i can send parameters in it), any ideas please?
Thanks in advance.
Fair warning, this type of question will get shot down by many SO moderators, but I'll give you some tips regardless:
Controller actions are single-use. If you find yourself with duplicate code in multiple controllers (or, needing to call a controller function from another controller), that's a sure sign you should move that code to a model or library.
Models are object-specific, not action-specific. I wouldn't have a model dedicated to logins, unless you have multiple types of logins (most apps/sites just have member logins, but you might have administrators, etc. that are stored in a different table from the rest). Instead, have a User_model class, and make function login($email, $password) a method of that class.
Controller-to-model interaction should be very concise. If you find yourself with 30 lines of code passing data back and forth between the same controller and model, you might be trying to do too much with that one controller action.
Keep your models fat, controllers skinny, and views dumb.

Resources