Why does Laravel group RESTful methods the way they do? - laravel

I'm brand new to Laravel and am working my way through the Laravel 6 from Scratch course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.
I've finished the first several sections of the course and am a little confused about some of the concepts around the whole RESTful idea. The instructor, who seems very good and experienced with Laravel, describes 7 methods that are going to be part of pretty much any CRUD (Create Read Update Delete) application (and most applications are CRUD in nature.) He says naming of these 7 methods should be consistent with this:
index - a list of all the resources in a collection e.g. all articles in a blog
show - display a specific resource from a collection e.g. a specific article in a blog
create - create a new instance of a resource e.g. add a new article to a blog
store - save a new instance of a resource to a data store like a database
edit - modify the contents of an existing resource e.g. change the title of an article
update - save the modified resource to a data store
destroy - remove a resource from a collection e.g. delete a blog article
I'm a little puzzled by this division of work into 7 separate methods. It seems to me that Create and Store belong together in a single method; ditto for Edit and Update. Creating a new record has two phases: displaying an empty form to gather up the data needed to construct a new article, then validating the data and storing it on the database. By the same token, changing an existing record consists of two phases: displaying the current data in a form and letting the user change what needs changing, then validating it and sending it to the database (or back to the user for corrections).
I would also argue that to be consistent with the approach they've used for create/store and edit/update, destroy should be divided into two methods, Destroy and Remove, where Destroy displays the full record that the user wants to remove with two buttons at the bottom: Delete and Cancel. Then, if the user clicks on Delete, they go to a Remove method that actually deletes the record f from the database.
I've been coding for a fair while and I've never seen a system where the user was allowed to delete any important record without first being shown the record and being asked if they're sure they want to delete it. Now, maybe that's fallen out of fashion and I didn't notice but it seems a pretty prudent thing to do.
So why are the methods what they are, at least as RESTful is implemented in Laravel?

It seems to me that Create and Store belong together in a single method
Well, Laravel generate all those methods thinking in a server-side rendered app. So in a SSR, before you store your data, you must be able to see a creation form.. that's why this create() function exists. The create(), normally, should return a view that will show the user the valid fields to create a resource, this is all done in a GET request. Then, when the users hit the "create"/"add" button, it will reach the store() method that will implement the logic to persist this data storing a new record in your database, this is done in a POST request.
The same goes for edit()/update().
I've been coding for a fair while and I've never seen a system where the user was allowed to delete any important record without first being shown the record and being asked if they're sure they want to delete it
That is because those validations are commonly implemented in the client-side, so, you do this with JS in your front-end, for validations of that kind you shouldn't hit the server.
So why are the methods what they are, at least as RESTful is implemented in Laravel?
Finally, for a RESTful API you don't need all of those methods. Just index, show, store, update and delete ones. If you just need this kind of methods in your controller, you could exclude the create/edit ones by adding the --api flag when creating your controller through Artisan. From the documentation:
API Resource Routes
// ...
To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:
php artisan make:controller API/PhotoController --api

Related

Adding attribute to a user when register in Laravel 5.1

When a user Register, I want to add location data for the user.
I get those with GeoIP.
So, each time a user is created, I would like somewhere to add Country, City, etc.
I was thinking about setting Hidden fields in view, but I think it a hugly way to do it, and I'm sure there is a better way to do...
Any Idea???
Any time I create a record that needs extra data, involves inserting additional records into additional tables, etc, I create a service class. Something like "UserCreator" then I pass it the input, do any additional operations, wrap multiple database calls in a transaction and so on.
That said there are so many ways to do what you want. You could Input::merge(...) then save, you could separate the process of creating a user from your controller / route function, etc.
If you are just getting started with Laravel and/or your project is rather simple, then you probably want to look at Input::merge
I solved it using Request Contructor as said here in laracast
In the Form Request's constructor I inject \Illuminate\Http\Request. I can then add my value to the request instance as such:
public function __construct(\Illuminate\Http\Request $request)
{
$request->request->add(['date_of_birth' => implode('-', $request->only('year', 'month', 'day'))]);
}

Laravel, custom functions in for views

I am having someone create a bunch of templates (themes) for a website, and want to keep data passed to the views flexible.
For example, with the users in the system I want to be able to supply the top x users and the most recent x users. In my controller I don't want to pass this data to the view, because he might just need the top 5 users and I am querying the top 10 - or worse, I might only get the top 5 and he wants the top 10.
I am thinking there would be two ways to do this.
1 - A view "helpers" file, which could contain functions like. getTopUsers($count) and getNewestUsers($count) which would do the model / repo call.
2 - Create a view presenter to keep these extra functions. I've had a look and there seems to be two main presenter packages - https://github.com/ShawnMcCool/laravel-auto-presenter and https://github.com/laracasts/Presenter
Maybe there is a better way?
There could be half a dozen of these, for various models...
I would pop some client side code into your views and access a route to a controller action (which returns JSON by default) and conditionally add that particular snippet into your view (via a variable passed to the view that determines if the person is logged in). Then you can apply an auth filter to your route to protect it.
Note: with this approach you can pass url parameters to your action. This means you can tell your controller to limit your results more easily.
This is a very interesting question, my friend. What I can think of is the following
1) cheap way, just query 10 or whichever the biggest number, and then pass a variable $count to the view or let view pass a variable to the sub view
2) api call, if you'd like to do AJAX call, then as others suggested, you could just design a new route, getData?count=5.
Normally it's not easy to meet all requirements, and practically speaking in the prototype stage, it'll be more cost-effective to write fixed function like getData5, and getData10, or just make two pages :) it'll be a lot faster than coming up another new architecture design and then realize in the end nobody really uses them.

cakePHP - creating new user account, several problems

I have two tables, users and tokens.
Each user have a activated field and each token have the {id, token, user_id, created} fields.
The way the app should work is:
On the creation, the app will -
make sure that the activated field is empty (to avoid manipulations to the submitted data).
a token will be created in the tokens table.
On update, the app will -
NOT create a new token.
NOT allow an update of any kind to the activated field.
check if a new email has been submitted, and if so: will create a new token and set the activated field to false.
I know how to activate the account through the controller and how to setup the router for that.
What I need is mainly the model configuration.
For example:
I think that the token creation should be done in the afterSave method, so - how do I determine if the method is called by an update or by a create operation?
Thanks for any help
yossi you can also specify the fields that should be saved from the form though - a whitelist of fields it is ok to save in you $this->save() call. That way you can stop a hacker passing an ID in the request, and you should just set it in the controller yourself then with $this->Token->id = whatever you have, I would personally use saveField ('activated) in conjunction with this (just saves a single field!). Fat models is best if you can but get it working first then refactor it if you have got stuck. Better than wasting lots of time writing perfect first time.
You question is unclear. If you have a default value for a field, then why not set it in the database rather than doing something in aftersave? If you need to do something that should be done only in certain circumstances, then write a custom method in your model to perform the tasks you want either on creation or update.
Edit
So, if your record has an id, then you know it exists in the database. So, the simple thing to do is (in any method) check to see if the model has an id field and that it is not empty. If it's empty, then you know that you are creating a record and you can do x task. If it isn't, then do y task.
if(isset($modelData['ModelName']['id']) && !empty($modelData['ModelName']['id'])){
//This is an update
} else {
//This is a new record
}

CakePHP Auth Loads Too Many Session Variables

Using CakePHP2.0 Beta I managed to write a custom login handler for my existing database schema. All's well, except that upon logging in I printed out the session variables stored and what Cake's Auth component did is store the entire record from the "Member" table (where my usernames+hashes come from) in session. It is storing an array with data fields that are totally irrelevant to the session. For instance it stores the date the member was created, their address, etc. All pretty useless information for me as I basically only need their ID and maybe username, name, email address.
The offending lines for me are found in: /lib/Cake/Controller/Component/AuthComponent.php line 512. It states,
$this->Session->write(self::$sessionKey, $user);
So my custom authenticate component returns $user and it throws this whole thing into the session. Now, I don't want to go about editing in the core libraries because this project is definitely going to be upgraded when 2.0 comes out. Is there any way to store less information in sessions? I want to keep this whole thing more lightweight.
Possible solution: Change my custom authentication component to only return the fields I need into the $user variable. Are there any concerns about what data I should/shouldn't be returning?
I've solved the problem using my "possible solution". In /app/Controller/Component/auth/MyController.php, I changed the "ClassRegistry::init($userModel)->find" method to have a parameter for 'fields' where I specify only the fields I need. Works like a charm.

Proper way of deleting records with Codeigniter

I came across another Stackoverflow post regarding Get vs Post and it made me think. With CI, my URL for deleting a record is http://domain.com/item/delete/100, which deletes record id 100 from my DB. The record_id is pulled via $this->uri->segment. In my model I do have a where clause that checks that the user is indeed the owner of that record. A user_id is stored in a session inside the DB. Is that good enough?
My understanding is, POST should be used for one time modification for data and GET is for retrieving regards (e.g. viewing an item or permalink).
You really ought to require a post request when deleting. In CodeIgniter this could be as simple as checking $this->input->post('confirm')
Part of the justification is you don't want data changed on a get request. Since you said you are requiring the person be the owner, there still is the problem that some one puts an image with the source being http://domain.com/item/delete/100 Using post isn't a cure-all as you can do post requests from javascript so it would still be possible for a malicious user to create the delete request if you aren't properly filtering input.
I should admit that I'm a bit of a purist and just feel requiring post is the right way. Its how the standards were written (okay you could argue it should be a DELETE request but browsers typically don't support them) and in other cases you really need to use them (there have been cases of web crawlers deleting pages).
If you want to have the delete link be http://domain.com/item/delete/100 then you could display a confirmation message with a form that does a post action as confirming the deletion.
I hope this helps,
Bill

Resources