Laravel Controller and helper file: Undefined variable in view - php

I have an issue trying to use in my controller a function located in an helper file which is auto-loaded. I already used helper functions in some controllers but this function doesn't work and I don't understand why. I have different resources that use a similar code for the controller index() function for example. So my aim is to make functions that I can use in different controllers in this way.
Here's the error I get: "Undefined variable: articles" in the view file ArticlesIndex.blade.php
Helper function:
function res_index($collection,$viewName,$varName) {
if(!$collection->isEmpty()) {
$collection->take(10);
return view($viewName, compact($varName));
} else {
return 'Nothing';
}
}
And here's my index() function located in the controller:
public function index()
{
$articles = Article::all();
return res_index($articles,'ArticlesIndex','articles');
}
Thanks a lot !

Return value, returned by res_index:
return res_index($articles,'ArticlesIndex','articles');

Related

Laravel paginate() method doesn't work in index controller method

I am a newbie to Laravel development. I have checked the documentation of Laravel for using database pagination. I found that I can use paginate(numbreOfLines) to paginate.
Whenever I write in my controller:
public function index()
{
$users= User::paginate(3);
}
It doesn't work. I don't know why. I am using Laravel 5.4
I believe that you have defined table name in Model User.php file
public function index()
{
$users= User::paginate(3);
return $users;
}
You need to return the results to the view , that's why you get nothing.
public function index()
{
$users= User::paginate(3);
return view('view.blade.php')->with('users', $users);
}

Calling a Controller Method in a View - Codeigniter [duplicate]

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>

Where should I define a custom function in CodeIgniter and how can I use it in every page?

I'm a newbie in CodeIgniter. I want to use the following function and needs to be run in every page. I'm calling the function in the top header of the view. Even though different subviews are loaded in the content below, the navigation bar should load this function in order to count notifications and messages on every run.
function count_records_in_table($table, $where)
{
$this->db->select('count(id) as rows');
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
foreach($query->result() as $r)
{
return $r->rows;
}
}
first create the common model
then put this function on it and load this model in
$autoload['model'] = array('mdl_common');
autoload file in config
finally you can use your function by calling model common like this
$this->mdl_common->count_records_in_table("table_name","where");
you can use in every page you want try it it will helps .
Here is suitable solution
First create one file say common.php in application/libraries/common.php
Now write below code in common.php file
class Common extends CI_Controller
{
public function customFailMessage($msg)
{
$xml = new SimpleXMLElement('<Response/>');
$xml->addChild('status','success');
$xml->addChild('msg',"my message");
print ($xml->asXML());
die;
}
}
Now call you function from any of your controller like this
class Ws_plan extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('common');
}
public function test()
{
$this->common->customFailMessage();
}
}
Hope you got idea how to use common function in all controller

Cakephp error:Call to a member function find() on a non-object

I am having problems with my code. When I try to debug my web application I get the following error message....Call to a member function find() on a non-object.....here is my code
class TeamsController extends AppController {
var $name = 'Teams';
function index() {
$this->set('teams', $this->team->find('all'));
}
function Welcome() {
}
}
I am trying to display records from my MySQL database. Now with that said, I did this tutorial and I followed the instructions down to the tee.....but somehow my code has bugs. The only difference between my code and the code of the tutorial I did is the variable names...and the controller names....and the I dont have the hello world function... Here is a sample of the code from the tutorial I did....
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function hello_world() {
}
}
With that said, am I suppose to declare an instance of an object to get this to work?
It's likely a case sensitivity issue:
function index() {
$this->set('teams', $this->Team->find('all'));
}
If not, ensure your controller has access to the Teams model (e.g. $uses).

How to call codeigniter controller function from view

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>

Categories