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 :

  1. view()->share('variable_name',$value);
  2. session(['variable_name'=>$value]);
  3. 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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.