1

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:

  1. id
  2. name
  3. value

Now I want to access each option value in my master.blade.php file. what is the best way to do it.

tereško
  • 58,060
  • 25
  • 98
  • 150
Hujjat Nazari
  • 868
  • 1
  • 9
  • 13

2 Answers2

2

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

Community
  • 1
  • 1
Emeka Mbah
  • 16,745
  • 10
  • 77
  • 96
  • thanks bro, What if I try to access this options in every view? I mean globally. – Hujjat Nazari Feb 17 '16 at 09:42
  • 1
    check out my answer here: http://stackoverflow.com/questions/29715813/laravel-5-global-blade-view-variable-available-in-all-templates/29716181#29716181 – Emeka Mbah Feb 17 '16 at 13:55
1

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

Qazi
  • 5,015
  • 8
  • 42
  • 62