How to access table data without model in view - laravel

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

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>

How to set global variables from database in Laravel 5.4

I'm facing the same problem very often in various projects - I need to set some global variables from database and be able to receive them in anywhere in laravel - views, controllers, models. Is it possible? Or what is the most easy way to do this?
Why I need this? For language translations. I need them not cached and saved in file. For website options which can be taken from any place of app. For website language to set, because I don't want to make /language/ prefix on url.
Sorry if this question can be a duplicate, but none of the answers in similar questions worked in a way I have explained.
You can try view composers for sharing data globally to all views.
public function compose(View $view)
{
//get value from database
$options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
//render to view
$view->with('options', $options);
}
The $options variable (model) would be available in every view.
To share data with all controllers define variables in base controller to access them in controllers which inherit base controller
class Controller extends BaseController
{
public $options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
}
you can access it using
class LoginController extends Controller
{
public function dashboard()
{
//access here using
$x = $this->options;
}
}
Like this you can create a base model and use the inherit property to access data globally in models.
Hope it will be useful for you. The options variable may contain all the options from database.
Another way to do this is to create a helper class:
1> Add line to composer.json:
"autoload": {
"files": [
"app/Http/helpers.php"
],
2> Create file:
app/Http/helpers.php
3> Add code:
function o($code = null) {
$option = \Option::where('code', $code)->first();
return $option->value;
}
4> Use where you need:
echo o('option_code')
This works in Controller and View, before any render if called. Here can be checked session, config, cookies and etc.
the best way to access a variable everywhere in your project is using sessions. you can store everything in sessions and access it everywhere in your controllers, models and views.
Read the topic: https://laravel.com/docs/5.5/session#using-the-session

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 reusable sections

I have a table of data from a database that I want to display on various pages of my website. Ideally, i would like to just have an include or something that will go off and get the data, and return the html table. The html and data will be identical everytime I need to use this.
I wanted to know the best way of doing this
Thanks
EDIT
If this helps, something similar to a Django "inclusion" custom tag...for any django developers reading
you need to pass the variable $data to the view method.
This is your code:
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view');
}
Please change it to this in order to load the $data into the view:
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view',$data);
}
You should use a function in a model to fetch the data you need. Your controller calls the model function and sends the returned information to a view. You don't need to use traditional php includes with Codeigniter. I recommend a review of the user guide. It's very good and will tell you all the basic stuff you need to know to develop with CI. But to get you started, you watn to use Models, Views, and Controllers. Your url will tell CI what controller and function inside that controller to run. If your url is
http://www.example.com/my_controller/load_my_view
Then CI will do what is inside the load_my_view function in the my_controller controller. function load_my_view in turn instantiates a model "my_table" and runs a database query, returns information that the controller sends to the view. A basic example follows:
Your model
class my_table extends CI_Model{
function my_data(){
$this->db->select('column_1,column_2,column_3');
$this->db->from('my_table');
$query = $this->db->get();
if($query->num_rows()>0){
$result = $query->result();
}
else{
$result = false;
}
return $result;
}
}
Your controller
class my_controller extends CI_Controller{
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view');
}
}
Your View
<ul id = "my_db_results">
<?php foreach($my_results as $result):?>
<li><?php echo $result->column_1." : ".$result->column_2." ( ".$result->column_3." )";?></li>
<?php endforeach;?>
</ul>
It looks like a good oportunity to use cache: http://codeigniter.com/user_guide/libraries/caching.html
Ok, so here is one thing that worked for me, but its definitely not perfect.
I created a view in which made a call to the model getting the data then put the data into a table. This way, I only have to include this view to put the table anywhere.
I understand this completely ruins the point of having a MVC framework, but hopefully it demonstrates what I want to do...and it works

Resources