Home > Software design >  how to solve compact undefined variable error in laravel 5.8
how to solve compact undefined variable error in laravel 5.8

Time:03-15

I want to fetch data from database in table but it show me undefined variable error in view please help me to solve this problem

my controller

class showAttendanceController extends Controller
{

    public function index()
    {
        $users=DB::select('select * from requests');

        return view('showAttendance',compact('users'));
    }

my view

@foreach ($users as $user)
    <td>{{$user->date}}</td>
    <td>{{$user->Name}}</td>
    <td>{{$user->Misid}}</td>
    <td>{{$user->semester}}</td>
    <td>{{$user->Department}}</td>
    <td>{{$user->section}}</td>
    <td>{{$user->Attendance}}</td>

My Route

Route::get('/showrecord','showAttendanceController@index')->name('showrecord');

CodePudding user response:

Controller:

public function index()
{
  $users = DB::table('requests')->get();  
  return view('showAttendance',compact('users'));
}

View:

@foreach($users as $user)
        <td>{{$user->date}}</td>
        <td>{{$user->Name}}</td>
        <td>{{$user->Misid}}</td>
        <td>{{$user->semester}}</td>
        <td>{{$user->Department}}</td>
        <td>{{$user->section}}</td>
        <td>{{$user->Attendance}}</td>
@endforeach

CodePudding user response:

first of all, it's better to create your table using migrations in order to have Database Consistency. Further try to use models to interact with Database for example

namespace App;

use Illuminate\Database\Eloquent\Model;

class deposit extends Model
{
    //
    protected $keyType = 'string';
    protected $table = "deposit";
    protected $fillable = [
        'uid', 'amount', 'title', 'description'
    ];

}

and then you can use it in your controller

     $deposit = deposit::find($request->deposit_id);
            if($deposit){
             return $deposit
            } else { 
             return 'Some Error'}

CodePudding user response:

first of all you have to use DB in your controller

public function index()
{
 $users = DB::table('table_name')->get();  
 return view('showAttendance',compact('users'));
}

than you have to confirm your return view file location is right or not.Exmple if your showAttendence file is inside a folder you have to use

return view('foldername.showAttendence',compact('users));
  • Related