Laravel 5.1 Passing data (controller -> view) - laravel-5.1

I'm new to Laravel, I want to understand what is the best approach to share values from controllers to views: I have found few ways of doing it :
view()->share('variable_name',$value);
session(['variable_name'=>$value]);
return view('viewname')->with('variable_name'=>$value);
Is there any difference between these ways?
Also, is it a good practice to share data from the model(from design point of view)?
Thanks

1) The best and valid approach, passing data from controller to view is
return view('viewname')->with('variable_name'=>$value);
data will be accessible in specific page views
2) While this is also valid approach, but this case is used, when you want to share your data in all views on any page you access
view()->share('variable_name',$value);
the above line means, when you access any page, in all pages your variable_name will be available eg:
welcome
contact us
about us
gallery
admin/listing etc
3) session() is used for storing small amount of information across the all website pages. eg: we store, user basic information, last login time, redirect url etc(it depends upon requirement), be default session has some expiry time, around 20min, means if you don't do any activity, your session will be expire.
I hope that make sense for you

Related

MVC Session for storing user information vs DB call

I have a user details area that is split out on to about 6 different pages (details, contact, preferences, etc). I need to have access to all of the user details after login.
I was going to add the user details to a Session like this after login so that I could access them all from the different pages without having to call the database on each page;
Session["name"] = name;
Session["bla"] = bla;
However I've googled and some people talk about saving the session to a database, which sounds like i may as well not use it. The users may not access every page or require access to all of this information, so it could be seen as a bit needless to add them all to a Session.
Is there a recommended practice for storing user information like this? I also have an ID that needs to be shown on every page. Perhaps something like this is better for a session and the more detailed info pages to keep with their own database calls?
.
EDIT: I am using Umbraco 7.2.8 and am getting the member details from the MemberService. I am worried that it hits the database each time though. My code to get the Member details and also the custom member properties (currently in each controller) is;
// Get the details of the user currently logged in
var profileModel = Members.GetCurrentMemberProfileModel();
// Get the custom properties for the member
var member = memberService.GetByUsername(profileModel.UserName);
model.Firstname = profileModel.Name;
model.Email = profileModel.Email;
model.specialID = member.Properties["specialID"].Value.ToString();
Any pointers would be great!
If you use the built in Umbraco Member service (link 1, link 2) to manage your users, you'll have a relatively simple way to get current logged in member. It's also easy to manage the member profiles with custom data fields and so on. No need to think too much about sessions and such.
Edit: take a look in here - specifically the GetCurrentPersistedMember() method - Umbraco is using caching to save current member
There are three popular ways to store the data in memory
1) Caching
2) Session
3) Static Classes
Out of above three I will always prefer Caching, as numerous articles suggested and I too agree that Sessions are comparatively slow than Caching & Static classes. I would always prefer caching over sessions.
But whatever you use, make sure that you are initializing them at single place, so that all the sessions and caching used in whole application is known to every developer. This will help in code re-usability & reduces the duplication of initializing the same value again in system. It will also help in code-maintainability.

Struts2 how to keep form values when navigating between pages?

I’m using struts2 + spring3 for my project. Please help me to resolve this problem.
In my app, (a.jsp) relate to --> (aAction.java).
From the main menu, user can access a.jsp. There are so many fields in the a.jsp that user need to key in data. In the middle of the page, user needs to go another page (b.jsp) to add some more details. (b.jsp page is not a popup window) After adding data to b.jsp, user needs to come back to a.jsp. How can I retain a.jsp page data?
Only one action use for both pages (aAction.java).
1) I can keep hidden variables in b.jsp and populate data again in a.jsp. But there are so many
fields in a.jsp. So this way is tedious.
Is there any way to handle this problem with bean scope? Or any other way to do?
There are several ways to do this
use redirectActions in struts.xml. When defining results you can set the type to redirectAction. Then you can redirect to another action and pass params that will be added as parameters to the url
http://struts.apache.org/release/2.1.x/docs/redirect-action-result.html
use localStorage instead of session storage. Limit is 5 MB. Care needs to be taken when using session storage as it can affect the server's performance
if you are using struts, you can make your own type converter for passing any object. Alternatively you could create an string array of the values you want to persist and pass it as a param in struts.xml (see above). Struts has built in type converter for persisting string arrays between pages/actions
you could also save them in cookies and then delete the cookies as soon as the values are not needed as there is a limit on the number of cookies browsers can support
I usually use session storage as a last resort for the reason mentioned above

Store data between action

What the best way to store data between two controller action?
Example:
I have a big array of posts id ["2907", "2334", "2309",.... N] i create it in first step confirm and go to second step to another controller action.
Another controller action render data (calendar, groups), i select date in calendar, choose group and create one more array of date-time data confirm and go to another action
Another action manipulate with this array and array of posts id, and render date again the data what i whant to save after confirm, data safe in DB and clear all array from session.
I store all array between action in session like session[:posts_ids] = params[:posts_ids] and flash[:date_day] ||= params[:date_day]. I think it do not work for a really big data array. May be the best way store it in redis ?
This is largely opinion-based, but I think your two best options are:
Use Redis, Memcached or some other server-side cacheing solution to store the objects in memory until you need them.
Make your app more ajax-y and do all of the selection and temporary
persistence of those arrays client-side.
Session size is limited by the underlying strategy, rather than a hard limit for sessions in general. CookieStore is the default and will allow ~4k of data, because browser cookies are limited to that size. If you use database-backed sessions, you're only limited by your database server.
You should also keep in mind that using sessions to store data between requests isn't very RESTful.

ASP.NET MVC : Create an ambient value

I have a simple web-site. Almost every action takes int toonId as an argument (toonId does not equate to the user: one user can own multiple toons).
At the moment I provide that value to every view from controller, and every link and submit button sends this value back to the controller.
This works. I am just looking for an easier way to accomplish this (AOP comes to mind).
I use cookies to persist "favorite/default toon", and this works fine (used with ActionAttribute, that takes toonId from cookie and passes is to the toonId argument, if toonId wasn't provided). But I want to support cookie-less sessions as well.
Question: What is an easy way to add ambient variable to the page, without passing it explicitly all over? Such that it would work with cookie-less browsers.
Is Viewstate a way to go (which isn't supposed to be in the MVC)?
Is server-side session a way to go?
This is exactly what session is meant for.
There is no page lifecycle in asp.net mvc, hence no viewstate.
I believe you can automatically pass query string parameters for use cookie-less browsers if you plug in your own implementation of IRouteHandler. I have not tried it though. I found an example of implementing IRouteHandler although it does not show how to implement the query string parameter functionality.
I'm not clear on what 'toonid' represents. If it's 'ambient per user session', then as womp stated, Session state would work well for this. However, if it's somethign that has a larger scope (e.g. a colleciton of toonids that are commonly accessed by all users) then teh Cache would be a better and more scalable strategy.

Redirect After Post in ASP.NET MVC

I am using the Redirect After Post pattern in my ASP.NET MVC application. I have
the following scenario:
User goes to /controller/index where he is asked to fill a form.
Form values are POSTed to /controller/calculate.
The Calculate action performs calculation based on input and instantiates a complex object containing the results of the operation. This object is stored in TempData and user is redirected to /controller/result.
/controller/result retrieves the result from TempData and renders them to the user.
The problem with this approach is that if the user hits F5 while viewing the results in /controller/result the page can no longer be rendered as TempData has been expired and the result object is no longer available.
This behavior is not desired by the users. One possible solution would be instead of redirecting after the POST, just rendering the results view. Now if the user hits F5 he gets a browser dialog asking if he wants to repost the form. This also was not desired.
One possible solution I thought of was to serialize the result object and passing it in the URL before redirecting but AFAIK there are some limitations in the length of a GET request and if the object gets pretty big I might hit this limitation (especially if base64 encoded).
Another possibility would be to use the Session object instead of TempData to persist the results. But before implementing this solution I would like to know if there's a better way of doing it.
UPDATE:
Further investigating the issue I found out that if I re-put the result object in TempData inside the /controller/result action it actually works:
public ActionResult Result()
{
var result = TempData["result"];
TempData["result"] = result;
return View(result);
}
But this feels kind of dirty. Could there be any side effects with this approach (such as switching to out-of-process session providers as currently I use InProc)?
Store it in the Session with some unique key and pass the key as part of the url. Then as long as the session is alive they can use the back/forward button to their heart's content and still have the URL respond properly. Alternatively, you could use the ASP cache, but I'd normally reserve that for objects that are shared among users. Of course, if you used the parameters to the calculation as the key and you found the result in the cache, you could simply re-use it.
I think redirect after post makes much more sense when the resulting Url is meaningfull.
In your case it would mean that all data required for the calculation is in the Url of /controller/result.
/controller/calculate would not do the calculation but /controller/result.
If you can get this done thinks get pretty easy: You hash the values required for the calculation and use it as the key for the cache. If the user refreshes he only hits the cache.
If you cant have a meaningfull url you could post to /controller/index. If the user hits F5 calculation would start again, but a cache with the hash as key would help again.
TempData is generally considered useful for passing messages back to the user not for storing working entities (a user refresh will nuke the contents of TempData).
I don't know of more appropriate place than the session to store this kind of information. I think the general idea is keep session as small as possible though. Personally I usually write some wrappers to add and remove specific objects to session. Cleaning them up manually where possible.
Alternatively you can store in a database in which you purge stale items on a regular basis.
I might adopt a similar idea to a lot of banks on their online banking sites by using one-time keys to verify all POSTs. You can integrate it into a html helper for forms and into your service layer (for example) for verification.
Let's say that you only want to post any instance of a form once. Add a guid to the form. If the form does not post back and the data is committed then you want to invalidate the guid and redirect to the GET action. If say the form was not valid, when the page posts back you need a new (valid) guid there in the form waiting for the next post attempt.
GUIDs are generated as required and added to a table in your DB. As they are invalidated (by POSTS, whether successful or not) they are flagged in the table. You may want to trim the table at 100 rows.. or 1000, depending on how heavy your app will be and how many rendered but not yet posted forms you may have at any one time.
I haven't really fine tuned this design but i think it might work. It wont be as smelly as the TempData and you can still adhere to the PRG pattern.
Remember, with PRG you dont want to send the new data to the GET action in a temp variable of some sort. You want to query it back from the data store, where it's now committed to.
As Michael stated, TempData has a single purpose -> store an object for one trip only and only one trip. As I understand it, TempData is essentially using the same Session object as you might use but it will automatically remove the object from the session on the next trip.
Stick with Session imho rather than push back in to TempData.

Resources