I have for example this code in my HomeController:
public function index() {
$comments = Comment::get_recent();
$top = User::get_top_uploaders()->get();
$top_something = User::get_top_something_uploaders()->get();
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
return View::make('index') ->with('data', $data)
->with('comments', $comments)
->with('top', $top)
->with('top_something', $top_something);
}
It works great, but I need to make another couple of view with the same data not only for index but also for other pages like comments(), post()...
How to make this in HomeController that I don't need to make it copy and paste those variables in every controller?
Pass your data using share method:
// for single controller:
class SomeController extends BaseController {
public function __construct()
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
View::share('data', $data);
}
}
For all controllers you can put this code in BaseController's constructor
If the data is displayed using the same HTML each time you could put that piece of HTML into a partial and then use a View Composer.
Create a view and call it whatever you want and put in your HTML for the data.
In templates that need that partial include it #include('your.partial')
In either app/routes.php or even better app/composers.php (don't forget to autoload it)
View::Composer('your.partial', function($view)
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
$view->with('data', $data);
});
Now whenever that partial is included in one of your templates it will have access to your data
Related
As it is quite easy to get data from database in admin panel,but the case is that how can i get/view those data to front view , front view contains the data from several table. Could you please help me ? How can i manage those front pages easily ?
There are a lot of ways, but this is what I normally do.
Use a separate controller method (say index() HomeController) for the frontpage, and create an array of all the variables with the data from database and pass it on to the page. Let's say our homepage has some slider images, some blog posts, and and our team section, then your HomeController would look something like this:
class HomeController extends Controller
{
public function index()
{
$data = []; //your empty array
$data['sliders'] = Slider::all(); //data from sliders table
$data['posts'] = Post::all(); //data from posts table
$data['teams'] = Team::all(); //data from teams table
return view('frontend.index',compact('data'));
}
Now you can access all these in your frontend blade (here index.blade.php) as such:
#foreach($data['teams'] as $key=> $value)
//your loop code
#endforeach
Hope this helps.
In the wonderfull world of laravel this is super easy. But first let me dive a into the structure of laravel a bit.
It all begins with the controller. In Laravel, Controllers a re meant to group assiociated request handling logic within a single class. A basic resource controller would look like this:
class DomainController extends Controller
{
public function index(){} // list domains
public function create(){} // show create form
public function store(Request $request){ } // handle the form POST
public function show($id){} // show a single domain
public function edit($id){} // show edit page
public function update(Request $request, $id){} // handle show edit page POST
public function destroy($id){} // delete a domain
}
Now how can you return the data to the view?
Let's say we want to generate a list of all users using the index function from the controller.
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
With this return statement we will get a view and in that view we will have the $users variable available because of the use of the comapct function.
Now if we want to show a simple list:
#foreach($users as $user)
<li>{{$user->name}}</li>
<li>{{$user->age}}</li>
#endforeach
I need your help. I new in Laravel.
I want to get all categories and subcategories into my navigation bar so on every page. I have a Category model. How to get all categories? Can I just using something like
Category::all()->get() etc.
in my layout, is it right to call from the layout?
You should use view composers to pass a variable to all pages. First create a view composer in App\View\Composer;
namespace App\View\Composers;
use App\Category;
use Illuminate\View\View;
class InjectCategory
{
protected $categories;
public function __construct(Category $categories)
{
$this->categories= $categories;
}
public function compose(View $view)
{
$categories= $this->categories->all();
$view->with('categories',$categories);
}
}
Then you should add the view composer to the AppServiceProvider's boot method.
public function boot(Request $request)
{
$this->app['view']->composer(['includes.frontend.menu'], Composers\InjectCategory::class);
}
Now you can use the $categories values from your menu.blade.php and include it to top of any page you want to show navigation.
Some how when i was working on a Blog Project i also had the same issue which i solved by sharing the data with all views which is quite easy and simple way.
in your app/Provider/AppServiceProvider.php file in boot Method add below code:
public function boot()
{
$categories = Category::all();
view()->share('categories', $categories);
}
and now you can access $categories in every view for more detail info visit this link.
How can I set a "default" view and/or controller so it will be always called no matter the route?
I have tried with:
(routes.php)
Route::get('/*', function(){
return View::make('master');
});
and:
Route::get('*', function(){
return View::make('master');
});
But gives me NotFoundHttpException;
Related question: Is there a better way to do this than setting it in the routes.php?
Thanks!
Laravel have something called Controller Layouts, then in your controller you can create a variable named $layout and set it to a master or default view:
class Controller extends BaseController
{
protected $layout = 'layout.master';
public function getIndex() {
$data[];
$this->layout->content = View::make('myview', $data);
}
Now in the layout.master view you can access the $content variable.
Codeigniter gives a white screen every time a form is posted:
Here is the controller logic [controllers/account.php]:
class Account extends CI_Controller
{
public function create()
{
if($this->input->post(NULL, TRUE)){
$params = $this->input->post();
//add validation layer
$accountOptions = array($params are used here)
$this->load->model('account/account', 'account');
$this->account->initialize($accountOptions);
$this->account->save();
}
$header['title'] = "Create Free Account";
$this->load->view('front_end/header', $header);
$this->load->view('main_content');
$content['account_form'] = $this->load->view('forms/account_form', NULL, TRUE);
$this->load->view('account/create', $content);
$footer['extraJs'] = "account";
$this->load->view('front_end/footer', $footer);
}
}
Here is the Account Model logic [models/account/account.php]:
class Account extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function initialize($options)
{
//initialize
}
}
The view first loads fine then after filling the form and clicking submit, just white page.
I tried to add __construct to the controller and load account/account from there, the form does not even load. Any ideas?
I just found the problem:
- The Model account has duplicated definition and the error_reporting was off!
You shouldn't have two classes with the same name Account (the controller and model). Check your server and/or Codeigniter log it should show up there.
I advise you to call your controller class Account and your model class M_Account. You can then rename the model to account whenever you load it, just like you did:
$this->load->model('account/m_account', 'account');
public function __construct()
{
parent::__construct();
$this->load->model("account/account");
}
you load model,library and helper files in construct dont load to inside a function
I am trying to extend the CI_Controller class to load my global page header file so I don't have to load it at the beginning of every single controller method. It doesn't seem to be working. I know the Controller extension itself works... if I remove the call of the model method from the constructor and load it from my controller method, the rest of the controller extension works fine. But when I load the model method from within the constructor of the controller extension, I get a blank page(I haven't generated the main content yet).
Any ideas?
application/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
var $user = array();
function __construct(){
parent::__construct();
$this->load->model('member');
if($this->session->userdata('member_id')){
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
$this->member->update_activity($this->session->userdata('member_id'));
} else {
$this->load->helper('cookie');
if(get_cookie('Teacher Tools Member Cookie')){
$this->member->auto_login(get_cookie('Teacher Tools Member Cookie'));
} else {
$this->user = $this->member->default_info();
}
}
$this->load->model('template');
$this->template->overall_header();
}
}
application/models/template.php
<?php
class Template extends MY_Model {
function __construct(){
parent::__construct();
}
function overall_header($title = 'Home'){
$data = array(
'BASE_URL' => base_url(),
'MAIN_NAVIGATION' => $this->main_navigation(),
'TOOLBAR' => $this->toolbar()
);
return $this->parser->parse('overall_header.tpl', $data);
}
MY_Model is an extension of the CI_Model class to load member information into $this->user.
I think response generation is done in Controller's method and all HTML pieces that you might have gets glued there. So if you are calling /controller/method_a then method_a will be responsible for returning response whereas in constructor you cannot set response.
I agree with you on setting important data in Constructor once so that you don't have to do this again and again in each method. I think you should assign output to some Controller level variable and then use that variable in your Controller's method.
I' am sure you got my point.
For this reason there is a config/autoload.php:
$autoload['model'] = array('YourModel');