问题
I am trying to combine data to table that i had already created. And this is the code which will display it. The two table name is students,teachers. In this code i am getting an error message of
Undefined offset: 0 (View: C:\xampp\htdocs\schoolmanagement\resources\views\displaycombinedata.blade.php)
please help me out.
<head>
<title>
Display Combined Data
</title>
<h1>Display Combine Data from Database</h1>
</head>
<body>
<table>
<thead>
<th>S.No.</th>
<th>Student Name</th>
<th>Student Class</th>
<th>Student Age</th>
<th>class Teacher</th>
<th>Teacher salary</th>
</thead>
<tbody>
<?php for($i=1; $i<=DB::table('students')->count(); $i++):?>
<tr>
<?php $result=DB::table('students')->where('students_id','=',$i)->get();
?>
<td>{{($result[0]->students_id)}}</td>
<td>{{($result[0]->students_name)}}</td>
<td>{{($result[0]->students_class)}}</td>
<td>{{($result[0]->students_age)}}</td>
<td>{{($result[0]->class_teacher)}}</td>
<?php $result1= DB::table('teachers')->where('teachers_name','=',$result[0]->class_teacher)->get();
if($result1 == null) {?>
<td>NA</td>
<?php } else{?>
<td>{{($result1[0]->salary)}}}</td>
<?php } ?>
</tr>
<?php: @endfor ?>
</tbody>
</table>
</body>
回答1:
You're getting the "Undefined offset: 0" error because
$result=DB::table('students')->where('students_id','=',$i)->get();
is empty. and in this code,
<td>{{($result[0]->students_id)}}</td>
you're trying to get data from the first record of an empty array.
Instead, you should first check if the result is empty, and try to get the property only if it's not empty.
@if (!empty($result))
<td>{{($result[0]->students_id)}}</td>
<td>{{($result[0]->students_name)}}</td>
<td>{{($result[0]->students_class)}}</td>
<td>{{($result[0]->students_age)}}</td>
<td>{{($result[0]->class_teacher)}}</td>
@endIf
As a note, you really should not be directly querying the database within your Blade file!
回答2:
Just change
if($result1 == null)
to
if(count($result1) > 0)
or just if(count($result1))
since 0
is equal to false
.
The reason $result1 == null
doesnt work is because the query builder returns an empty collection instance when there is no records.
来源:https://stackoverflow.com/questions/50612342/laravel-v5-6-error-showing-this-undefined-offset-0-view-c-xampp-htdocs-scho