Passing variables to views in Laravel - laravel

In CodeIgniter you can pass a data array to views as in:
$this->load->view("view_name", array("key" => "value"));
and then access the variable in the view simply as $variable_name.
I'm trying to achieve the same thing in Laravel without necessarily storing the data in the session. The answers that I've seen suggest doing something like:
return view("view_name")->with("variable_name", $variable_value);
But doesn't that store it in the session? I'm looking to simply pass the variables directly to the view so as to avoid cluttering up the session with things that I'm passing to various views from controller methods.
Any help is much appreciated! Thanks.

You can use compact() to pass an array of the variables in your controller to your view. The compact() function will create an array from the variable names passed into it.
Controller class
public function showDashboard()
{
$total_sales = Sale::sum('price');
$average_sales = Sale::avg('price');
return view('dashboard.show',compact('total_sales','average_sales'));
}
blade file
<p>
Total sales made is {{$total_sales}} at average of {{$average_sales}}
</p>

Related

Laravel pass data between views

I have a view with a few variables that I want to pass to a new page and prepopulate a form with them.
$data->title
$data->catid
$data->category
$data->groupName
The "vanila way I could make a url like something.com?var1=something&var2=something etc.
But how can I do this in laravel?
Considering you can redirect to a page with GET parameter. For example, "something.com?var1=something&var2=something", You can actually pass this data to another view in Laravel. Let's assume you want to pass var1 and var2 variables to another view.
You will redirect user to the URL containing two variables as GET parameters, You will also execute Controller function that will handle that route. Let's assume that following is your web.php or routes.php file.
Route::get('firstpage","SomeController#view1");
Route::get("secondpage","SomeController#view2");
Now, in view2 method of the SomeController, You can check if those variables exist or not. Here is an example of var1 and var2.
public function view2()
{
if(isset($_GET['var1'])){
$var1 = $_GET['var1'];
}
// Similar for var2
}
This is how you can pass variables between views.
The best way IMHO is using sessions.
session()->put('data', $data);
And to retrieve it and to check if the key exists:
if (session()->has('data')) {
$data = session('data'); //array
}
If you use the $data in session() only once you can pull it session()->pull('data'); //array
A word of caution if you use database sessions. You may have to change the field 'payload' from TEXT to MEDIUMTEXT if $data holds larger amounts of data.
The use of sessions is not search engine (SEO) friendly. If that matters, the easiest way to make the url is $str = http_build_query($data); and to build the url \URL()->route('your.route').'?'.$str;
To access the data from the URL: $title = \Request::query('title');

How to access table data without model in view

I want to know is there any way to access table data without passing it from controller to view in laravel 5 ?
I have an Options table in my database that stores all my project options. it has three column:
id
name
value
Now I want to access each option value in my master.blade.php file.
what is the best way to do it.
If you understand what MVC is all about then you should know that passing a variable from controller to your view is the best practice. View is simply used for presentation and should only be used for presentation purpose for the sake of separation of concern.
With that been said the best approach is:
Create a model for options then pass it through your controller to the view.
For example:
use App\Option;
PageController extends Controller{
public function __construct(Option $option){
$this->option = $option;
}
public function about(){
$options = $this->option->list('id','value');
return view('about', $options);
}
}
To make variable global in all view see my answer here:
Laravel 5 - global Blade view variable available in all templates
Well there can be multiple ways available, but passing your Table data directly into views is not a recommended way, It would be much better if you follow the proper way, means from Controller to Model. Well its upto you. here is my suggested possible ways.
Method 1 (about which you are asking)
in your master.blade.php file, you can also do this,
<?php
$v = new \App\Message(); // your model object
echo $v ->testmeee(); // its method
?>
Method 2
If you are trying to use your Table data globally(means you want options data should be available on all pages/views), then this one is highly suggested way.
Goto your App/Http/Providers/AppServiceProvider.php file
view()->composer('*', function ($view)
{
$user = new \App\User();
$view->with('friend_new_req_count', count($user->getLoggedinUserNewFriends()));
});
now this variablefriend_new_req_count with data would be available in all views (only in views) means you can access in view {{$friend_new_req_count}}

Is good practice for view sending param by assign to controller property?

For sending param to view, document in CodeIgniter use as following:
$data['name'] = $this->name;
$data['color'] = $this->color;
$this->load->view('you_view',$data);//Load view with $data param
But currently i use like this:
//Controller file
$this->params = [Big Object or Array ];//Here I assigned my OJBECT or Array to controller property PARAMS
$this->load->view('you_view');//***** Wthout send with load view*******
//View file
$var_dump($this->params);//Notice after I print_r( $this) i found that it is current controller, that why i use without sending params during load view, but i afraid any problem or make my system slow.
In many different ways you can pass variables to the view, for example through controller as you did, then through config file, model, language file, or defining a variables with define(), but then the point of MVC model was to separate data, logic and design, so i don't thing your way is a bad way, just not in the spirit of idea of MVC. Do you get any better performance?

Calling model functions in a view in Laravel 4?

I am using a function to write a query, and I am trying to return the variable the function returns and use it in a view. In my model:
Fan.php
public function sample_query() {
$count = User::where('fbid', '=', 421930)->count();
return $count;
}
In the view I am simply trying to call it with:
#sample_query();
This is not working. I am new to this type of thing, and I suppose I don't know how to access the data pulled by queries in the model in the view. Please let me know if there is a better way, or why this isn't working. Thank you!
For your question it seems View Composer will solve your problem
View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".
View::composer('profile', function($view)
{
$view->with('count', User::count());
});
for more info read this
starting from the supposition that you have a User class:
{{ User::sample_query() }}

Codeigniter: Calling a method from a view

Here's my model, what it does is pulls a particular post from a user. Each post may also have comments, which are stored in an array called comments. I have everything working and I'm able to display the post along w/ the comments. The issue is, each comment has a post_date that displays when the comment was made. I need to call the function that "converts" the date into something like "3 weeks ago." The method TimeAgo is located in my user_model.php page. The excerpt shows a variable called data that's actually for the post, the comment is embedded inside the array and I loop through that in my view.
So the question is, is there a better way of handling this or do I have to call the TimeAgo method from within the view page?
Note, I'm using mongodb but it shouldn't matter if it's mongodb or mysql. Same thing ...
user_model.php
$query = array("_id" => new MongoId($plan_id), "username" => $username);
$fields = array("plan_title", "comments", "post_date");
$data = $collection_plans->findOne($query, $fields);
$data['date'] = self::TimeAgo($data['post_date']->sec);
$data['username'] = $username;
return $data;
If my understanding is correct I'd put the TimeAgo method inside a library or helper, then (auto)load whenever necessary and process the date before passing it to the view from within the controller.
this would allow you to access that method from within another model if required, or indeed any other part of your CI app, rather than from just within user_model.php
You call the model method from the controller and put it into a variable. You then pass the var to the view.

Resources