loadmodel dont work why? - php

in the sections_controller i use loadmodel to print username in sections/index file but i get error :
Notice (8): Undefined variable: user [APP\views\sections\index.ctp, line 3]
public function index ()
{
$this->loadModel('User');
$user = $this->User->find('all');
$this->Section->find('threaded', array('order' => array('Section.created ASC')));
$this->set('data','user');
}
in the sections/index
<div><?php echo $user['User']['username']; ?></div>

You have a typo, try :
$this->set('data',$user);
and then in your view :
<div><?php echo $data['User']['username']; ?></div>
Hope this helps !

You're not assigning the variable properly, try this instead:
$this->set('user', $user);
$user pointing to your find result and set as user, since that's what you're trying to call in your view. Or alternatively use the compact notation to achieve the same:
$this->set(compact('user'));
What you are doing now is setting a variable called data with the string value user, so when you would do this in your view:
echo $data;
It would return user as a string in your view.
EDIT
Since a find('all') will return an array, make sure you loop over the results in your view as well, like this:
foreach($user as $u) {
echo $u['User']['username'];
}
Or if you want a specific result, call it's array key, which for the first user would be:
echo $user[0]['User']['username'];

Related

How can I pass value from blade into controller in Laravel? [duplicate]

Im passing data to my blade view with return View::make('blog', $posts); and in my blade view I'm trying to run an #foreach ($posts as $post) I end up with an error saying that $posts isn't defined.
My question is how would the $posts array be called?
You can pass data to the view using the with method.
return View::make('blog')->with('posts', $posts);
As of Laravel 5, the View::make() facade method from the 2013 accepted answer has been deprecated. Passing data to the view is now done using the view() helper function like this:
return view("blog", ["posts"=>$posts]);
Or, the same thing:
return view("blog", compact("posts"));
This can be combined with the with() method if desired:
return view("blog", compact("posts"))->with("message", "Comment posted");
Documentation is available here.
If you want to pass just one variable to view, you may use
In Controller
return view('blog')->withTitle('Laravel Magic method.');
In view
<div>
Post title is {{$title}}.
</div>
If you want to pass multiple variables to view, you may use
In Controller
return view('blog')->withTitle('Laravel magic method')->withAuthor('Mister Tandon');
In view
<div>
Post title is {{$title}}.Author Name is {{$author}}
</div>
You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with() methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge, for instance), you might compute $variables (which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)
Tips1:
Using With(), This is a best practice
return view('about')->withName('Author Willson')->withJob('Writer');
return View::make('home')->with(compact('about'))
return View::make('home')->with('comments', $comments);
Tips2:
Using compact()
return view(about, compact('post1','post2'));
Tips3:
Using Second Parameters:
return view("about", ["comments"=>$posts]);
controller:
use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}
index:
<h1> posts</h1>
#if(count($this_will_be_used_as_variable_in_views)>0)
#foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
<p> {{$any_variable->created_at}} </p>
</ul>
#endforeach
#else
<p> empty </p>
#endif
Hope this helps! :)
use TCG\Voyager\Models\Jobtype;
class FormController extends Controller
{
public function index()
{
$category = Jobtype::all();
return view('contact', compact('category'));
}
}
use your model
assign it to a variabel
pass the object to the view
Here is an example:
You can also do the same thing in another way,
If you are using PHP 5.5 or latest one then you can do it as follow,
Controller:
return view(index, compact('data1','data2')); //as many as you want to pass
View:
<div>
You can access {{$data1}}. [if it is variable]
</div>
#foreach($data1 as $d1)
<div>
You can access {{$d1}}. [if it is array]
</div>
#endforeach
Same way you can access all variable that you have passed in compact function.
Hope it helps :)
You can also do like this
$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;
return view('your_viewname_here',$arr_view_data);
And you access this variable to view as $var1,$var2,$var3
You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);
You can pass your table data to view using compact.
$users = RoleModel::get();
return view('super-admin',compact('users'));
You can also write for passing multiple data from your controller to a view
return \View::make('myHome')
->with(compact('project'))
->with(['hello'=>$hello])
->with(['hello2'=>$hello2])
->with(['hello3'=>$hello3]);
OK all the answers tell you how to pass data to the view but no one explains how to read it in the view .
if you use :
//Routes/web.php
...
Route::get('/user', function () {
return view('profile', [
'variable1' => 'value1' ,
'variable2'=> 'value2' , // add as much as you want
]);
});
To read these variables use in your views (in this example it's profile.blade.php file):
#if($variable1)
<p> variable1 = {{ $variable1 }}</p>
#endif
Laravel does all the necessary work and creates $variable1 for you .
For example, you have an array with your data.
$array1 = $data;
$array2 = $data;
From your controller you can pass this variable using compact. You can pass as many array as you want.
return view('data.index',compact('array1','array2'));
Here data is a folder in view and index is the file with extension index.blade.php
In view you can call the arrays like this
#foreach ($array1 as $something)
// some operation
#endforeach
For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way
In the controller, you define the variables you want to pass as global and you attribute the values to these variables.
Example global $variable; $variable = 1;
And now in the view, at the top, simply do
<?php global $variable;?>
Then you can now call your variable from any where in the view for example
{{$variable}}
hope this helps someone.

How to pass data to view in Laravel?

Im passing data to my blade view with return View::make('blog', $posts); and in my blade view I'm trying to run an #foreach ($posts as $post) I end up with an error saying that $posts isn't defined.
My question is how would the $posts array be called?
You can pass data to the view using the with method.
return View::make('blog')->with('posts', $posts);
As of Laravel 5, the View::make() facade method from the 2013 accepted answer has been deprecated. Passing data to the view is now done using the view() helper function like this:
return view("blog", ["posts"=>$posts]);
Or, the same thing:
return view("blog", compact("posts"));
This can be combined with the with() method if desired:
return view("blog", compact("posts"))->with("message", "Comment posted");
Documentation is available here.
If you want to pass just one variable to view, you may use
In Controller
return view('blog')->withTitle('Laravel Magic method.');
In view
<div>
Post title is {{$title}}.
</div>
If you want to pass multiple variables to view, you may use
In Controller
return view('blog')->withTitle('Laravel magic method')->withAuthor('Mister Tandon');
In view
<div>
Post title is {{$title}}.Author Name is {{$author}}
</div>
You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with() methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge, for instance), you might compute $variables (which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)
Tips1:
Using With(), This is a best practice
return view('about')->withName('Author Willson')->withJob('Writer');
return View::make('home')->with(compact('about'))
return View::make('home')->with('comments', $comments);
Tips2:
Using compact()
return view(about, compact('post1','post2'));
Tips3:
Using Second Parameters:
return view("about", ["comments"=>$posts]);
controller:
use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}
index:
<h1> posts</h1>
#if(count($this_will_be_used_as_variable_in_views)>0)
#foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
<p> {{$any_variable->created_at}} </p>
</ul>
#endforeach
#else
<p> empty </p>
#endif
Hope this helps! :)
use TCG\Voyager\Models\Jobtype;
class FormController extends Controller
{
public function index()
{
$category = Jobtype::all();
return view('contact', compact('category'));
}
}
use your model
assign it to a variabel
pass the object to the view
Here is an example:
You can also do the same thing in another way,
If you are using PHP 5.5 or latest one then you can do it as follow,
Controller:
return view(index, compact('data1','data2')); //as many as you want to pass
View:
<div>
You can access {{$data1}}. [if it is variable]
</div>
#foreach($data1 as $d1)
<div>
You can access {{$d1}}. [if it is array]
</div>
#endforeach
Same way you can access all variable that you have passed in compact function.
Hope it helps :)
You can also do like this
$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;
return view('your_viewname_here',$arr_view_data);
And you access this variable to view as $var1,$var2,$var3
You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);
You can pass your table data to view using compact.
$users = RoleModel::get();
return view('super-admin',compact('users'));
You can also write for passing multiple data from your controller to a view
return \View::make('myHome')
->with(compact('project'))
->with(['hello'=>$hello])
->with(['hello2'=>$hello2])
->with(['hello3'=>$hello3]);
OK all the answers tell you how to pass data to the view but no one explains how to read it in the view .
if you use :
//Routes/web.php
...
Route::get('/user', function () {
return view('profile', [
'variable1' => 'value1' ,
'variable2'=> 'value2' , // add as much as you want
]);
});
To read these variables use in your views (in this example it's profile.blade.php file):
#if($variable1)
<p> variable1 = {{ $variable1 }}</p>
#endif
Laravel does all the necessary work and creates $variable1 for you .
For example, you have an array with your data.
$array1 = $data;
$array2 = $data;
From your controller you can pass this variable using compact. You can pass as many array as you want.
return view('data.index',compact('array1','array2'));
Here data is a folder in view and index is the file with extension index.blade.php
In view you can call the arrays like this
#foreach ($array1 as $something)
// some operation
#endforeach
For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way
In the controller, you define the variables you want to pass as global and you attribute the values to these variables.
Example global $variable; $variable = 1;
And now in the view, at the top, simply do
<?php global $variable;?>
Then you can now call your variable from any where in the view for example
{{$variable}}
hope this helps someone.

passing sql query results from controller into view with code igniter

So I'm having this problem, it should be pretty simple, but I don't know why I can't figure it out. I"m new to the whole idea of MVC, and I'm trying to pass a database query from my controller into a view and display the results in the view. The way I'm doing it now says "undefined variable, sql" when I load the view. This is what I have:
CONTROLLER
function make_login()
{
//Select list of departments for dropdown
$this->load->database();
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
$this->load->view('siteheader.php');
$this->load->view('makelogin.php', $sql->result_array());
$this->load->view('sitefooter.php');
}
VIEW
<?php
foreach($sql->result_array() as $row)
{
echo $row['departmentName'];
}
?>
(If I just echo it out in the controller, it displays the results)
Any help would be awesome...
THANKS!
few tips ~
your make_login should be in a model. your controller will look something like this:
function make_login
{
$this->load->model('login_model'); // whatever you call it
$data['departments'] = $this->login_model->get_departments();
/* note - you don't need to have the extension when it's a php file */
$this->load->view('siteheader');
$this->load->view('makelogin', $data);
$this->load->view('sitefooter');
}
now in your model, have something like:
function get_departments()
{
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
return $sql->result();
/* you simply return the results as an object
* also note you can use the ActiveRecord class for this...might make it easier
*/
}
and finally, your view:
<?php
foreach($departments as $store)
{
echo $store->name . '<br />'; // your fields/whatever you want to output.
}
?>
The SQL query should be done in the model.
Cheap mnemonic device: the D in model = database.
In the Controller, you assign part of the $data array to the results of the query:
$this->load->model('blog_model');
$data['posts'] = $this->blog_model->getPosts();
// Load the view with the data
$this->load->view('blog', $data);
In the Model, you do the actual query:
public function getPosts()
{
// Method chaining supported in PHP 5
$this->db->select('*')->from('posts');
// Assign the query object to a variable
$query = $this->db->get();
// We don't want to return an empty result, so let's handle that error somehow
if (!$query->num_rows() > 0) {
die("There are no posts in the database.");
}
// Make a new array for the posts
$posts = array();
// For the purposes of this example, we'll only return the title
foreach ($query->result() as $row) {
$posts[$row->id] = $row->title;
}
// Pass the result back to the controller
return $posts;
}
Now, in the view, each element of $data will be its own variable:
<div class="post">
<?php foreach ($posts as $id => $title) : ?>
<h1 class="post-title"><?php echo $title; ?> (ID: <?php echo $id; ?>)</h1>
<p class="post-content">
.......
</p>
<?php endforeach; ?>
</div>
That's it!
It seems that either CI is confusing you or you are also new to PHP. They are just functions so you can't pass variables like that.
When passing an associative array it will take the key and make that into a variable with the value in the array, using native PHP functions. What Ross said is exactly what you are supposed to do.
Model: all database stuff
Controller: uses models to pass variables to views
View: outputs the variables (a view should never have any sql in it)
Also note that result and result_array have the same data but result returns objects and result_array returns associative arrays.
foreach($array as $row)
{
echo $row['departmentName'];
}
?>
You need to pass the $array in.
I am not sure what ->load->view() does and how it treats the incoming parameters.

CakePHP accessing other controllers

CakePHP Newbie :)
I am having trouble accessing another controller and passing that data to a view in one of my controllers:
In controllers/landings_controller.php:
var $uses = 'User';
function home() {
$userdata = $this->User->read();
$this->set(compact('userdata'));
}
In views/landings/home.ctp:
<?php
echo $this->userdata;
?>
When accessing /landings/home I get the following error:
Notice (8): Undefined property: View::$userdata [APP/views/landings/home.ctp, line 38]
I don't know what I am doing wrong. Any help?
Thanks!
$this->set('userdata', $userdata);
Compact returns a single array. $this->set expects two parameters.
http://book.cakephp.org/view/57/Controller-Methods
Correction:
set does in fact accept associative arrays (thanks Daniel Wright). Read below about using variables in views.
Also, variables are placed in scope -- not attached as members -- so you wouldn't do this in the view:
<?php echo $this->userdata ?>
but, rather:
<?php echo $userdata ?>
Assuming $userdata is a scalar, of course.
I think using compact is fine.You need know more about set().

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories