I'm slowly starting to come to grip with Laravel but keep having little issues doing basic things.
So this is what I have at the moment
A function and a function that is called by my route both in my webcontroller.php
// Function for printing out copyright year
function copyright_info($begin_year = NULL)
{
date_default_timezone_set('Europe/London');
if(empty($begin_year) || $begin_year == date('Y'))
echo date('Y');
else
echo $begin_year." - ".date('Y');
}
// function being called by route.php to get Restaurant Page
public function restaurant () {
$cookie = Cookie::get("basket");
return view('pages.restaurant', ['basket' => $cookie]);
}
Now all the first function does is print out something like 2013-2015 once the year is provided.
So I should be able to do something like this
public function restaurant () {
// use the function and get copyright year
$year = copyright_info('2013')
$cookie = Cookie::get("basket");
// pass data to the view including the year we just created
return view('pages.restaurant', ['basket' => $cookie, 'year' => $year]);
}
Now in my restaurant.blade.php file, I'm including my footer in my includes folder that is generic to all my pages like this #include('includes.footer'). Now the footer is what actually contains a div that requires the $year I have passed to the restaurant view. in my footer.blade.php I have this
<p style="font-size: 0.9rem">Copyright © {{ $year }} | xxx.com Limited</p>
Now I would assume that when I pass data to restaurant and footer is included in restaurant the data will apply to footer when it gets included in restaurant but that doesn't happpen.
After a lot of testing, I have now found out that my function doesn't produce any data at all. This is not because the function doesn't work also because in normal PHP it does
Any guidance appreciated
Try to pass $year from restaurant.blade to footer.blade
#include('includes.footer', ['year'=>$year])
So I figured it out.
Laravel will add the variable regardless of whether it is used in the main view or the include
Always, always make sure that your functions return something. From the question you can see that my function uses echo
Hope this helps someone in the future.
Related
I have a project in which is develop in codeigniter.
The project is like this:
-root
--controller
---Slider.php
--models
---My_data.php
--views
---slider_view.php
---giris.php
Slider.php
public function manset_al(){
$title['title']='manşet listesi';
$this->load->model('My_data');
$data['manset']= $this->My_data->get_manset();
$this->load->view('slider_view' ,$data);
}
My_data.php code is;
public function get_manset() {
// $sorgu =
// mysql_query("select * from manset, haberler
// where manset.onay='1' and manset.link=haberler.id and haberler.onay='1'
// order by haberler.id desc");
$this->db->select('*');
$this->db->from('manset as man, haberler as hab');
$this->db->where('man.link=hab.id');
$this->db->where('hab.onay=1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return $query->result();
}
slider_view.php code is:
foreach($manset as $row){
$baslik =$row->baslik;
$icerik =$row->icerik;
$link =$row->link;
$img_path =$row->img_path;
$giris =$row->giris;
$cikis =$row->cikis;
echo '
<div>
<img data-u="image" src="'.$img_path.'"/>
<div data-u="thumb"> <h5 style="color:white; margin:10px;">'.$baslik.' </h5> </div>
</div>';
}
Now when i called
http//example.com/index.php/Slider/manset_al
every think is ok - the slider is running.
But when i get the slider in giris.php with this code;
$this->load->view('slider_view');
it's not run and say: undefined variable manset;
how can ı fix it?
Thank you.
We're missing some details to quickly solve this one: namely, how is giris.php called, exactly? Without those details I can only give a general answer.
This error means that you are trying to access data in your template file that you haven't passed to the templating system. For instance, in your controller (Slider.php) you pass data off to the templates here:
$this->load->view('slider_view' ,$data);
The $data is the important part: codeigniter takes every entry in that array and creates a variable in the template system whos name corresponds to the name of each key. Therefore, foreach( $manset as $row ) works because $data has a key named manset that has each row in it. You can see that in giris.php you are specifically not sending any data to the template:
$this->load->view('slider_view');
Notice the lack of a second parameter. Of course your file structure implies that giris.php is itself a view file, which means that whatever controller method that called giris.php needs to be the one sending data out to the view. So generally, that is the answer: whatever controller is ultimately calling giris.php needs to be sending the slider information out to the templating system, but isn't. Without more details on how giris.php is actually called, that is as specific as I can get.
I hope the title does not sound too confusing, but I had no idea how to name my problem.
Brief intro:
I'm using Zend 1.1X.
At the moment I've been working with a search form sending few parameters via POST.
Now I have to change it to use GET, I have a route created looking similar to that:
"search/what/:what/shape/:shape"
and so on, I also have 2 optional parameters which takes null as default.
I'm trying to generate an URL (using Zend View Helper Url) at form's action, but it throws an exception:
Uncaught exception 'Zend_Controller_Router_Exception' with message what is not specified
I Now don't have idea what should I do. If I change my route to "search" only, it then sends the form correctly, but I end up with "search?what=XXXX&shape=YYYY" instead of "search/what/XXXX/shape/YYYY".
Is there any way that could be handled the way I like??? :>
#EDIT
I think this should also be mentioned - I have a different form, similar one, pointing to a route without parameters specified as well and the uri gets "translated" to the form of "key/value" pairs. The only difference between them is that the first one does not use Url helper, instead has the method part hard-coded and my form is being submitted programatically (button => jQuery stuff => submit). Would that make a difference here, as I believe it should not? :>
I hope any possible source of this behaviour will come up to you, because I'm really stuck at the moment and I simply can't find what's wrong..
Thanks in advance!
With the GET method a form generates an url like this: action?param1=val1¶m2=val2&....
I see two solutions:
The first is to regenerate the URL by javacsript, we can imagine something like this:
<form method="get" id="id_form">
....
</form>
<script>
var objet_form = document.getElementById('id_form');
function gestionclic(event){
var url = objet_form.action;
for(var i = 0; i < objet_form.length; i++){
url += "/" + objet_form[i].name + "/" + objet_form[i].value;
}
objet_form.action = url;
}
if (objet_form.addEventListener){
objet_form.addEventListener("submit", gestionclic, false);
} else{
objet_form.attachEvent("onsubmit", gestionclic, false);
}
</script>
But I don't think this is a good solution.
The second is to manage it with a plugin:
For the plugin, it must be declared in the bootstrap.
For example:
public function _initPlugins(){
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PRoutage());
}
with this example, the application/plugins folder, create the PRoutage.php plugin like this:
class Application_Plugin_PRoutage extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
...
}
}
and with the variable $request you have access to your data as an array with $request->getParams().
We can imagine something like this:
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$param = $request->getParams();
$what = "";
$shape = "";
if (isset($param['what']) $what = $param['what'];
if (isset($param['shape']) $shape = $param['shape'];
if ($what == "XXXX" && $shape == "YYYY"){
$request->setControllerName('other_controler')
->setActionName('other_action')
->setDispatched(true) ;
}
}
I hope it will help you
I'm using Laravel localization to provide two different languages. I've got all the path stuff set up, and mydomain.com/en/bla delivers English and stores the 'en' session variable, and mydomain.com/he/bla delivers Hebrew and stores the 'he' session variable. However, I can't figure out a decent way to provide a language-switching link. How would this work?
I've solved my problem by adding this to the before filter in routes.php:
// Default language ($lang) & current uri language ($lang_uri)
$lang = 'he';
$lang_uri = URI::segment(1);
// Set default session language if none is set
if(!Session::has('language'))
{
Session::put('language', $lang);
}
// Route language path if needed
if($lang_uri !== 'en' && $lang_uri !== 'he')
{
return Redirect::to($lang.'/'.($lang_uri ? URI::current() : ''));
}
// Set session language to uri
elseif($lang_uri !== Session::get('language'))
{
Session::put('language', $lang_uri);
}
// Store the language switch links to the session
$he2en = preg_replace('/he\//', 'en/', URI::full(), 1);
$en2he = preg_replace('/en\//', 'he/', URI::full(), 1);
Session::put('he2en', $he2en);
Session::put('en2he', $en2he);
This is a post i posted originally on the laravel forums, but maybe it will help somebody else, so i post it here also.
I had some trouble with building a easy language switcher for my app, and the info on the forums where a little bit old (some posts), so i made this simple piece of code that makes it supereasy to change language on your app on the fly.
I have the language strings in my views as following:
{{ __('languagefile.the_language_string'); }}
And I get the languages with a URL, i think this is the best way, also its good for seo and for links that people share. Example:
www.myapp.com/fi/support (Finnish)
www.myapp.com/en/support (English)
www.myapp.com/sv/support (Swedish)
Ok, so the problem was that i wanted a easy way to change the language on the fly, without having to mess with sessions and cookies. Heres how i made it:
Make a library in your libraries folder called chooselang.php
Insert this code inside:
class Chooselang extends HTML {
/**
* Generate a Language changer link.
*
* <code>
* // Generate a link to the current location,
* // but still change the site langauge on the fly
* // Change $langcode to desired language, also change the Config::set('application.language', 'YOUR-LANG-HERE')); to desired language
* // Example
* echo Chooselang::langslug(URI::current() , $langcode = 'Finnish' . Config::set('application.language', 'fi'));
* </code>
*
* #param string $url
* #param string $langcode
* #param array $attributes
* #param bool $https
* #return string
*/
public static function langslug($url, $langcode = null, $attributes = array(), $https = null)
{
$url = URL::to($url, $https);
if (is_null($langcode)) $langcode = $url;
return '<a href="'.$url.'"'.static::attributes($attributes).'>'.static::entities($langcode).'</a>';
}
}
After this you are ready for getting your url switcher URL:s generated. Simply add them as you whould any other Blade links.
Example how to generate links for Finnish, Swedish and English (with Blade)
{{ Chooselang::langslug(URI::current() , $langcode = 'Fin' . Config::set('application.language', 'fi')); }}
{{ Chooselang::langslug(URI::current() , $langcode = 'Swe' . Config::set('application.language', 'sv')); }}
{{ Chooselang::langslug(URI::current() , $langcode = 'Eng' . Config::set('application.language', 'en')); }}
The above will generate URL:s that are always on the current page, and change the lang slug to the one you want. This way the language changes to the one you want, and the user naturally stays on the same page. The default language slug is never added to the url.
Generated urls look something like:
Fin
Swe
Eng
PS. The links are specially useful if you add them to your master template file.
You could have a Route to hand language change, for example:
Route::get('translate/(:any)', 'translator#set');
Then in the set action in the translator controller could alter the session, depending on the language code passed via the URL.
You could also alter the configuration setting by using
Config::set('application.language', $url_variable');
Controller Example - translate.php
public function action_set($url_variable)
{
/* Your code Here */
}
Just in case for future users if you want to use package for localization There is a great package at https://github.com/mcamara/laravel-localization. which is easy to install and has many helpers.
This question still comes in Google search, so here's the answer if you're using Laravel 4 or 5, and mcamara/laravellocalization.
<ul>
<li class="h5"><strong><span class="ee-text-dark">{{ trans('common.chooselanguage') }}:</span></strong> </li>
#foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<li>
<a rel="alternate" hreflang="{{$localeCode}}" href="{{LaravelLocalization::getLocalizedURL($localeCode) }}">
<img src="/img/flags/{{$localeCode}}.gif" /> {{{ $properties['native'] }}}
</a>
</li>
#endforeach
</ul>
NOTE that this example shows flags (in public/img/flags/{{locale}}.gif), and to use it you will need a bit of .css, but you can modify it to display the text if you want...
FYI. The mcamara/laravellocalization documentation has examples and a LOT of helpers, so look through the documentation on github. (https://github.com/mcamara/laravel-localization)
Try use Session's. Somthing like this:
Controller:
class Language_Controller extends Base_Controller {
function __construct(){
$this->action_set();
parent::__construct();
}
private function checkLang($lang = null){
if(isset($lang)){
foreach($this->_Langs as $k => $v){
if(strcmp($lang, $k) == 0) $Check = true;
}
}
return isset($Check) ? $Check : false;
}
public function action_set($lang = null){
if(isset($lang) && $this->checkLang($lang)){
Session::put('lang', $lang);
$this->_Langs['current'] = $lang;
Config::set('application.language', $lang);
} else {
if(Session::has('lang')){
Config::set('application.language', Session::get('lang'));
$this->_Langs['current'] = Session::get('lang');
} else {
$this->_Langs['current'] = $this->_Default;
}
}
return Redirect::to('/');
}
}
In Route.php:
Route::get('lang/(:any)', 'language#set');
I've been doing it like this:
$languages = Config::get('lang.languages'); //returns array('hrv', 'eng')
$locale = Request::segment(1); //fetches first URI segment
//for default language ('hrv') set $locale prefix to "", otherwise set it to lang prefix
if (in_array($locale, $languages) && $locale != 'hrv') {
App::setLocale($locale);
} else {
App::setLocale('hrv');
$locale = null;
}
// "/" routes will be default language routes, and "/$prefix" routes will be routes for all other languages
Route::group(array('prefix' => $locale), function() {
//my routes here
});
Source: http://forumsarchive.laravel.io/viewtopic.php?pid=35185#p35185
What I'm doing consists of two steps:
I'm creating a languages table which consists of these fields:
id | name | slug
which hold the data im gonna need for the languages for example
1 | greek | gr
2 | english | en
3 | deutch | de
The Language model I use in the code below refers to that table.
So, in my routes.php I have something like:
//get the first segment of the url
$slug = Request::segment(1);
$requested_slug = "";
//I retrieve the recordset from the languages table that has as a slug the first url segment of request
$lang = Language::where('slug', '=', $slug)->first();
//if it's null, the language I will retrieve a new recordset with my default language
$lang ? $requested_slug = $slug : $lang = Language::where('slug', '=', **mydefaultlanguage**')->first();
//I'm preparing the $routePrefix variable, which will help me with my forms
$requested_slug == ""? $routePrefix = "" : $routePrefix = $requested_slug.".";
//and I'm putting the data in the in the session
Session::put('lang_id', $lang->id);
Session::put('slug', $requested_slug);
Session::put('routePrefix', $routePrefix );
Session::put('lang', $lang->name);
And then I can write me routes using the requested slug as a prefix...
Route::group(array('prefix' => $requested_slug), function()
{
Route::get('/', function () {
return "the language here is gonna be: ".Session::get('lang');
});
Route::resource('posts', 'PostsController');
Route::resource('albums', 'AlbumsController');
});
This works but this code will ask the database for the languages everytime the route changes in my app.
I don't know how I could, and if I should, figure out a mechanism that detects if the route changes to another language.
Hope that helped.
Ok, I followed the instructions in the example perfectly. Ultimately, pagination works, kind of.
I get all of the pages listed: 1 | 2 | > | Last. Etc.
The first one is active, like it should be. I did the querying correctly as well, because each link will result in the correct query.
However, when I click on number 2, it will show me the next set of products correctly, but it will display the pagination from the first page.
Whatever pagination button I click on, will return the main pagination set: 1 (selected) | 2 | > | Last. It never changes! I'm loosing my patience, can someone help?
I think I might know whats going on. You need to tell the pagination library which segment of the URL holds the offset.
For example, if your URL is /products/browse/all/20, you need to tell CodeIgniter that the 4th segment holds the offset
$config['uri_segment'] = 4;
The default for the library is URL segment #3. If the offset in your URL is not in position 3 and you forget to tell the pagination library this, it will interpret the wrong segment as being the offset. This can lead to the kind of behaviour you describe above where the pagination does not appear to change.
I also came across same error and finally was able to fix it. Just thought to share the code script, may be someone will be able to use it.
=====> Controller
// Default function
function index()
{
// Display listing
$this->listing();
}
function listing($argDataArr = array())
{
// Initialize pagination
$pageArr['base_url'] = $this->config->item('categoryBeAction')."/listing";
$pageArr['total_rows'] = 15; //assume
$pageArr['per_page'] = 5; //assume
//You need to tell the pagination library which segment of the URL holds the offset.
$pageArr['uri_segment'] = 4; //URL eg: http://localhost/myproject/index.php/backend/category/listing/5
$this->pagination->initialize($pageArr);
// Get list of categories
// Create data array and pass data to get function
$dataArr['limitRows'] = $pageArr['per_page'];
$dataArr['limitOffset'] = $this->uri->segment(4); //the dynamic value from this segment will be used as offSet
$viewArr['listArr'] = $this->category_model->get($dataArr);
//rest of the code...
}
======> Model
function get($argDataArr = array())
{
//Select the fields required
$this->db->select('id, name, parent_id, status');
$this->db->from($this->config->item('tbl_category','dbtables'));
$this->db->where('parent_id', $parentId);
$this->db->limit($argDataArr['limitRows'], $argDataArr['limitOffset']);
$this->db->order_by("name", "asc");
$query_result = $this->db->get();
return $query_result;
}
======> View page
<!-- Pagination -->
<tr>
<td align="right">
<?php echo $this->pagination->create_links(); ?>
</td>
</tr>
Which example?
echo $this->pagination->create_links();
^^Is this in your view?
I dont understand what the layout is, in the view. I asked a question previously on the subject of templating in PHP, but I still dont quite understand. I assume that you create a general layout for the site and then include each specific view within that layout.... I would like to know how to go about doing this. Also, are should the templates be made using just html, because I also looked at these things called helpers.... I'm just confused on the View part of the MVC, and the actual templates and how they're made. I learn best with examples, If you guys have any.
Also, a more important question, lets say I had a form that a user saw only if he was logged in, would I control that in the view, or in the controller?
So Would i do
in the controller
include 'header';
if(isset($_SESSION['userID'])){
include 'form';
}
include 'footer';
or
in the template
<html>
<?php if(isset($_SESSION['user_id'])): ?>
<form>....</form>
<?php endif;?>
</html>
EDIT
So, is there an include statement from within the layout to see the specific view template? how so?
a layout is whatever you have around your main content area. Usually on a normal website it would be any sidebar,header,footer. Most of MVC framework provide the layout to avoid to repeat those parts in all views.
You can imagine if like you have two view cascaded
you actual view is rendered, this content is saved
the layout view (all the items around the content) are rendered and your content is included in that output
for your login question actually your would have to do both
on the controller and the view
$this->view->isLogged = isset($_SESSION['userID']);
in the view
<?php if($isLogged): ?>
<form>....</form>
<?php endif;?>
I hesitate to answer this question only because of the religious fervor that surrounds it.
To get a really good understanding of the issues behind the general concepts see This Wiki Discussion Page This is the discussion page around the wiki MVC article.
Here is the rule of thumb I like to follow (BTW I use CodeIgniter and it kind of sounds like you are too):
The "view" should have virtually no logic. It should only be HTML (in the web world) with peppered PHP that simply echos variables. In your example you would break out the form into its own view and the controller would determine if was loaded or not.
I like to look at it this way: The view should have no concept of where the data comes from or where it is going. The model should be view agnostic. The controller meshes data from the model and provides it to the view - and it takes input from the view and filters it to the model.
Here is a quick and dirty (untested - but it should get the point across) example:
Theapp.php (The App controller)
class Theapp extends Controller
{
var $_authenticated;
var $_user;
var $_menu; // array of menus
function __construct()
{
session_start();
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'])
{
$this->_authenticated = $_SESSION['authenticated']; // or some such thing
$this->_user = $_SESSION['user'];
}
$this->_menu = array("Logout", "Help", "More");
parent::__construct();
$this->loadView("welcome"); // loads primary welcome view - but not necessarily a complete "html" page
}
function index()
{
if (!$this->_authenticated)
$this->loadView("loginform");
else
{
$viewData['menu'] = $this->_menu;
$viewData['user'] = $this->_user;
$this->loadView("menu", $viewData);
}
}
function login()
{
/* code to authenticate user */
}
function Logout() { /* code to process Logout menu selection */ }
function Help() { /* code to process Help menu selection */ }
function More() { /* code to process More menu selection */ }
}
welcome.php
<h1> Welcome to this quick and dirty app!</h1>
All sorts of good HTML, javascript, etc would be put in here!
loginform.php
<form action"/Theapp/login" method="post">
User: <input id='user' name='user'>
Pass: <input id='pass' name='pass' type='password'>
<input type='submit'>
</form>
menu.php
Hi <?= $user ?>!<br>
Here's your menu<br>
<? foreach ($menu as $option) { ?>
<div class='menuOption'><a href='/Theapp/<?=$option?>'><?=$option?></a></div>
<? } ?>
Hope this helps.
If your not using a framework, then a simple way to have a layout and a view can be like so:
<?php
function layout($layout_params) {
extract($layout_params);
# Remember: $layout_content must be echoed for the view to be seen.
ob_start();
include "layout_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function view($view_params) {
extract($view_params);
ob_start();
include "home_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
#
# The variable $parameters is extracted and $params becomes a variable in the view as an array,
# $logged_in is also now avaiable in the view
#
$parameters = array("params" => array("name" => "joe"), "logged_in" => false);
$view_content = view($parameters); # => Returns the HTML content for home_page.php
# Now we need the layout content to include the view:
# The layout file will expect a variable called $layout_content to be the html view.
# So we need to set $layout_content to be $view_content
$parameters["layout_content"] = $view_content;
# We no longer need $view_content so we can unset the variable
unset($view_content);
# When $paramters is extracted it will have $layout_content as a variable:
$layout_content = layout_view($paramters); # => Returns the HTML content for the layout_page.php
# Now send the results to the browser
echo $layout_content;
?>