Undefined variable: sub inside the foreach loop in laravel - php

Controller:
public function dashboard()
{
$course = Course::all();
return view('content.dashboard',compact('course'));
}
View:
#foreach($course as $year)
$sub = \App\Models\SubCourse::where('course_id',$year->id)->first();
#dd($sub->id);
#endforeach
In the above code I am trying to get value of SubCourse but it throw an error i.e. Undefined variable: sub (View: C:\xampp\htdocs\example\resources\views\content\dashboard.blade.php). I don't know why? Please help me.
Thank you

You Can Accessing Model Like this in PHP Tag
#foreach($course as $year)
<?php
$sub = \App\Models\SubCourse::where('course_id',$year->id)->first();
#dd($sub->id);
?>
#endforeach

Related

Unable to fetch value at view.Laravel

I'm trying to fetch values at view passed from controller.
In my controller my syntax are:
public function index()
{
$vehicles=vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ad=ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ad as $ads) {
# code...
$popularvehicle[]=vehicles::where('id',$ads->id)->get();
// echo $popularvehicle;
}
return view('index',compact('vehicles','popularvehicle'));
}
In my views i've tried following:
#foreach($popularvehicle as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach
It gives an error of Undefined property: Illuminate\Database\Eloquent\Collection::$vname
I've also tried {!!$popularvehicle['vname']!!}. But it throws error like undefined index.
When i echo {!!$popularvehicle!!} it gives all the values required like [{"id":3,"vname":"Pulsar","lotno":"Ba 25 Pa","engine":"150","mileage":"35","kilometers":25000,"price":"120000","negotiable":"Yes","vcondition":"New","used":"3 month","manufacture_year":"2015","description":"Almost New","Company_cid":1,"Users_id":1,"Vehicle_Type_id":1,"created_at":"2017-01-12 15:08:41","updated_at":"2017-01-12 15:08:41"}].
How can i fetch the values of $popularvehicle? Can anyone help me? Will converting array to object help solve this problem. If yes, how can i do so?
The error is because -> is trying to point to the property of object $popularvehicles[] is an array:
$ads=ads::orderBy('views','desc')->get();
foreach ($ads as $ad) {
$popularvehicles[]=vehicles::where('id',$ad->id)->get()->toArray();
}
and then,
#foreach($popularvehicles as $popularvehicle)
#foreach($popularvehicle as $vehicle)
{{$vehicle['vname']}}
#endforeach
#endforeach
Note the changes made for naming conventions. Also, Model name is good to be singular.
Consider plural name
$popularvehicles = array();
foreach ($ad as $ads) {
$popularvehicles[]=vehicles::where('id',$ads->id)->get();
}
return view('index',compact('vehicles','popularvehicles'));
And use in view
#foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach
Try this:
Controller:
$popularvehicle = vehicles::where('id',$ads->id)->get();
// If you use $popularvehicles[] then you have to use one extra foreach() to retrieve the columns
View:
#foreach($popularvehicle as $vehicle)
{{$vehicle->id}} // for id
{{$vehicle->vname}} // for name
#endforeach
Try this:
public function index()
{
$vehicles = vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ads = ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ads as $ad) {
# code...
$popularvehicles[]=vehicles::find($ad->id);
}
return view('index',compact('vehicles','popularvehicles'));
}
And in your view:
#foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach

Redirecting the previous page after deleting a record

I'm a newbee in CI. I'm hoping that you can help me with my problem. :)
I am trying to redirect the previous page in my site which has the table containing the data from the database. I keep on getting the message
Fatal error: Call to a member function result() on a non-object in C:\xampp\htdocs\.....
Call to a member function result() on a non-object in C:\xampp\htdocs\findiningcebu.com\application\views\admin\SearchRestoDisplay.php on line 122
and the notice that says
Undefined variable: restaurantinfo....Backtrace:
File: C:\xampp\htdocs\findiningcebu.com\application\views\admin\SearchRestoDisplay.php
Line: 122
Here are my codes:
View:
<div class = "list">
<table border=2>
<tr style="font-size: 16px; background-color: rgba(26, 26, 38, 0.5);">
<th>Name</th>
<th>Logo</th>
<th>Cuisine</th>
<th>Action</th>
</tr>
<?php
$restoname= '';
$restologo= '';
$cuisine= '';
foreach($restaurantinfo->result() as $row)
{
$restoname= $row->restoname;
$restologo= $row->restologo;
$cuisine= $row->cuisine;
?>
Controller:
public function delete($id)
{
$this->load->model('AdminModel');
$delete = $this->AdminModel->delete($id);
$this->load->view('admin/SearchRestoDisplay');
}
public function searchresto()
{
$restoinfo = $_POST['restoinfo'];
$searchinfo = $_POST['searchinfo'];
$this->load->model('AdminModel');
$restaurantinfo['restoinfo'] = $restoinfo;
$restaurantinfo['searchinfo'] = $searchinfo;
$restaurantinfo['restaurantinfo']=$this->AdminModel->searchrestaurant($restoinfo,$searchinfo);
$this->load->view('admin/SearchRestoDisplay',$restaurantinfo);
}
Model:
public function delete($id){
$this->db->delete('restaurants',array('id'=>$id));
}
This is happening because result() is a method of the database class and you are trying to use this method on your $restaurantinfo and this looks like a simple array.
I recommend you that your $this->AdminModel->searchrestaurant returns something like this
function searchrestaurant(){
/*stuff*/
return $query->result_array();
}
this way you can simply foreach this on your view
foreach($restaurantinfo as $row)
{
$restoname= $row['restoname'];
$restologo= $row['restologo'];
$cuisine= $row['cuisine'];
}
The problem looks like you are trying to use a method of the database class on your view, where your query does not exists.
So, change the searchrestaurant function, or do the query on the view.. thing that I don't really recommend...
Hope that helps
In your delete function when you load the view, you don't pass the value '$restauranrinfo' that's why the restaurant details is missing in view. Fetch the restaurant details from database before load the view and pass the value in view.

Codeigniter: Sum contents of the records in a field

I am fetching some information from mysql database and I am displaying it using the following script(I am using Codeigniter).
Models
public function sum($field, $table, $userfield, $username)
{
return $this->db->query("SELECT SUM($field) FROM $table WHERE $userfield = '$username'");
}
Controller
public function save(){
$data = array(
'sum_simpan' => $this->user_m->sum('besar_simpanan', 'simpanan', 'id', $this->session->userdata('username'))->result()
); }
View
<div class="info-a">
<p>Total Simpanan Anda</p>
<h3><?php
foreach ($sum_simpan as $row) {
echo $row->besar_simpanan;
}
?>
</h3>
</div>
I want to do is sum the contents of a field, and display it in the view.
However I get an error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$besar_simpanan
Filename: anggota/simpanan.php
Line Number: 14
Would you please kindly show me how to do it.
Thanks in Advance :)
Change your model like this
public function sum($field, $table, $userfield, $username)
{
return $this->db->query("SELECT SUM($field) as total FROM $table WHERE $userfield = '$username'");
}
also the view
<h3>
<?php
foreach ($sum_simpan as $row) {
echo $row->total;
}
?>
</h3>

message undefined variable: news on view page

I'm new to PHP and CodeIgniter, and saw that there is many questions mentioning this and been trying them all but nothing seems to work. Everything is auto-loaded in configuration, the database is running and function for posting to database are working but writing to view page doesn't work at all. Except for displaying username, but for that I create a new variable on view page.
Controller
public function ShowNews()
{
$data = array();
$this->load->model('user');
$data['news'] = $this->user->getNews();
$this->load->vars($data);
}
Model
function getNews(){
$q = $this->db->get('News');
if($q->num_rows() > 0){
return $q->result();
}
return FALSE;
}
View
<?php foreach($news as $row) : ?>
<li><?php echo $row->Title; ?> </li>
<li><?php echo $row->Date; ?></li>
<?php endforeach; ?>
This is the error EDIT ves to news
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: news
Filename: admin/Pocetna.php
Line Number: 64
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: admin/Pocetna.php
Line Number: 64
Using WAMP, NetBeans with CodeIgniter. I saw it has to be something with passing data from controller to view but I can't figure it out and been trying few days already, but always having problems.
You're not passing $data to your view. Your controller should be like this:
public function show_news()
{
$this->load->model('user');
$data = [];
$data['news'] = $this->user->get_news();
$this->load->view('news', $data);
}
Your view should also be checking if $news is FALSE, because you'll have some issues with foreach if you loop over the value FALSE. Your model should also be returning result_array not result, foreach cam't loop over objects..
public function get_news()
{
$q = $this->db->get('News');
return($q->num_rows() > 0) ? $q->result_array() : FALSE;
}
Your view should look something like this:
<?php
if($news !== FALSE)
{
foreach($news as $row)
{
echo "<li>{$row['title']}</li>";
echo "<li>{$row['date']}</li>";
}
}
else
{
echo "No news to see here!";
}
?>
Your title also doesn't link up with the error in the post, so that's the solution to the one in the title.

CodeIgniter $data not passed from Controller to View

my controller is not passing $data to my view and I don't know why not. I'm reusing code from a previous project which worked fine and I certainly understand the idea of how $data passing is meant to work. But maybe I missed something when copying code over?
I put in the variable $data['hello'] in there just for testing purposes. As you can see from the output $hello isn't even getting through. The if fails and the else code is run correctly which means the view file itself is being loaded.
Controller:
function users() {
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
View:
<?php
echo $hello;
if ($users->num_rows != 0) {
foreach ($users->result() as $user) {
}
} else {
echo "No users.";
}
Output (abridged):
A PHP Error was encountered
Message: Undefined variable: hello
Line Number: 2
A PHP Error was encountered
Message: Undefined variable: users
Line Number: 3
A PHP Error was encountered
Message: Trying to get property of non-object
Line Number: 3
No users.
Edit: more info on request:
Model:
public function get_users($amount = 0, $offset = 0) {
$this->db->from('users');
$this->db->order_by('l_name', 'desc');
if ($amount != 0)
$this->db->limit($amount, $offset);
return $this->db->get();
}
I always do like this
change your model to
$query = $this->db->get();
return $query->result();
And in view
if (count($users)> 0) {
foreach ($users as $user) {
echo $user['name'];
}
} else {
echo "No users.";
}
Hope this helps
Regards
iijb
Just write $data = array(); before you are sending some data into $data array.
function users() {
$data = array();
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
I think you could solve your issue with some simple var_dump() checks.
Check what's coming out of your model by var_dump()ing $data['users'] - is this an object? What happens when you var_dump() $data['users']->result()?
Then, var_dump() $data in your view - does it have all the pieces?
Thing is, even showing us your model function doesn't prove that your getting a real data result. Check that. Your code looks okay at a glance so I don't think that is where the issue exists.
There is something very basic that is wrong. So get out of that controller and do a sanity check. First confirm that your welcome view is working. If it is go to the welcome controller and put this in the index method
$data['here'] = 'we are here' ;
$this->load->view('welcome_message', $data);
and then somewhere in the welcome.php view file
<?php echo $here ?>
You do not need to set this: $data = array();
However some people suggest it because that way even if you dont create any data variables you wont get an error if its in the view call $this->load->view('welcome_message', $data);
finally i would suggest looking at this
function users() {
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
lets see you have method called users, returning an object called users, and a view called users -- that could get confusing ! :-)

Categories