Laravel, custom functions in for views - laravel

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.

Related

What pattern or architecture should I implement by Laravel to structure this project?

The project is simple, and it has to do with formula 1 statistics. The UI looks a lot like a game menu. Going from "option" to "option" in the UI you end up in an "endpoint" page where the user can see the statistics of his like. It's tree structure where every "option" is a separate view on my project.
The user click "Race standings" to load a page. The user click a year on a form to see next page. The user click a race of that year then redirects to "race result" page. The logic for doing this is to create a nice UI so the user would like to spend time on the site and navigate through the pages.
I POST data from my view's forms to a controller's function. This function fetch the data from the database using my models and the post parameters, do the logic and return('thatView', compact('array' , 'array2', 'etc). php and javascript on the views manipulates the organized arrays fitting them into html. Arrays contains text data, for example array 1 could be the data of a race-result table.
The way my project is structure is very amateur. No patterns, no architecture, no anything good. Using directly the raceresult domain on the browser will result error. The needed parameters are missing as they cannot be set from the domain, it needs the previous page to post the data.
How could i structure my project better? What patterns could i use?
This is a basic overview you can follow:
App
-- Repositories
-- Services
Route > Controller > Service > Repository
Controller's method calls Service method. Here you put your business rules. If there as need of calling database, use repositories to do that.
It's clear for you?

Why does Laravel group RESTful methods the way they do?

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

Is There A Downside To Calling Models From Helpers In CakePHP?

A bit of context: I need to cache the homepage of my CakePHP site - apart from one small part, which displays events local to the user based on their IP address.
You can obviously use the <cake:nocache> tag to dictate a part of the page that shouldn't be cached; but you can't surround a controller-set variable with these tags to make it dynamic. Once a page is cached, that's it for the controller action, as far as I know.
What you can usefully surround with the nocache tags are elements and helpers. As such, I've created an element inside these tags, which calls a helper function to access the model and get the appropriate data. To get at the model from the helper I'm using:
$this->Modelname =& ClassRegistry::init("Modelname");
This seems to me, however, to be a kind of iffy way of doing things, both in terms of CakePHP and general MVC principles. So my question is, is this an appropriate way of getting what I want to do done, or should it ring warning bells? Is there a much better way of achieving my objectives that I'm just missing here?
Rather than using a Helper, try to put your code in an element and use requestAction inside of the element.
see this link
http://bakery.cakephp.org/articles/gwoo/2007/04/12/creating-reusable-elements-with-requestaction
This would be a much better approach than trying to use a model in your helper.
Other than breaking all the carefully-laid principles of MVC?
In addition to putting this item into an element, why not fetch it with a trivial bit of ajax?
Put the call in its own controller action, such that the destination URL -> /controller/action (quite convenient!)
Pass the IP back to that action for use in the find call
Set the ajax update callback to target within the element with the results of the call accordingly
No need to muck around calling Models directly from Views, and no need to bog things down with requestAction. :)
HTH

NoCaching A Small Part Of My CakePHP Page

I want to employ CakePHP's basic caching functionality on my site's home page. However, there is one element on the page that should display different data depending on the visitor's location, as determined by their IP address.
You can't wrap <cake:nocache> around variables that are set in the controller, which is where I was previously determining the location and getting the data. My question therefore is: where can I optimally set a (session?) variable to contain visitor location information before the controller? How can I use this information to populate an array of data for the nocached portion of the view, while completely sidestepping the controller action, which is no longer being called?
Any advice greatly appreciated!
Hmm, well, apparently CakePHP questions aren't of much interest to the world at large: only 8 views in 2 days :(
In any case I investigated a bit further and discovered that, while the <nocache> tags don't let you surround variables to make them dynamic, they DO allow you to make non-caching calls to elements or helpers. I therefore extracted the relevant part of my page into an element, and populated the data array by calling a helper function.
This did mean that I had to access the model from inside the helper with
$this->Modelname =& ClassRegistry::init("Modelname");
and I'm not sure this is necessarily the respectful CakePHP and/or MVC way of doing things, but at least it's some way towards a solution!

where should I save a complex MVC application UI state?

I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)
All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.
I've got a couple of apps made with some sort of framework built with classic asp.
This framework handles some CRUD stuff a little more complex than the examples I found.
Something like master-detail, filtering by example, paging, sorting and similars.
I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.
To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)
What do you think would be the finnest approach to achieve this kind of funcionality?
hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)
--
(added in response to tvanfosson)
basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...
I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???
I use different strategies depending on the character of the actual data. Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.
Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session. Generally these are things that if a user sets them in the current session they should remain sticky. I think filter settings and visibility are like this. If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.
Context-dependent settings -- like the current sort column or page number, are controlled using query parameters. Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control. Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST. Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go. This is probably more useful for sorting than it is for paging, but the principle applies equally.

Resources