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

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?

Related

Passing variables to views in 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>

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}}

MVC URL issues (Codeigniter)

I'm building a website using Codeigniter and I really like how in the MVC pattern URLs are used to reference controller methods. It seems very logical and intuitive however, I seem to be running in an array of issues with this very pattern!
So I am building an events website and currently I'm passing everything through one main Site controller, passing a number of parameters:
public function index($page = NULL, $city = NULL, $type_venue = NULL, $slug = NULL)
{
// if the page argument is empty show the homepage
if( ! ($page))
{
$page = 'home';
}
// create an array for passing to the views
$data = array(
'title_city' => $city,
'title_type_venue' => str_replace('-', ' ', $type_venue),
'locations' => $this->locations_model->load(),
'events' => $this->events_model->load($city, $type_venue, $slug),
'venues' => $this->venues_model->load($city, $slug)
);
// construct the page layout with the following views
$this->load->view('partials/head', $data);
$this->load->view('partials/header', $data);
$this->load->view('content/'.$page, $data);
$this->load->view('partials/footer');
}
This works fine, in that it loads content for the following URLs:
site.com/events/bristol/open-mic/city-varieties/another-incredible-event
site.com/events/bristol/open-mic/city-varieties/
site.com/events/bristol/open-mic/
site.com/events/bristol/
However if I want to pass anything else through this controller that isn't an event, i.e. register/user, I have to write a specific route for this!
Worth noting my routing is:
$route['(:any)'] = 'site/index/$1';
I could write separate controllers for each entity, i.e. events, venues, cities but each one would look largely like the above (correct?) in that each would need the parameters to get the data.
My question is - what is the best practice approach for developing long query strings like this? Is a single controller correct? It doesn't feel like it, but then multiple controllers would violate DRY, just because they all need so much similar data. Any help appreciated!
Avoid putting everything into a single controller; even further, in each controller, avoid putting everything into a single index function.
There is no need to write specific controllers for each function in Codeigniter - suggest you read that part again in the manual. Most of your routing will be done automatically for you if you follow the normal guidelines.
The more you try to use a single controller or function, the more you will have to add untestable, unmanageable, unscalable conditional code later.

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