Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

opv's avatar
Level 1

Laravel access one more from another controller.

I am trying to retrieve all students from the UserController but when I dump students all array I get empty collection in my view. Is the middleware preventing access to the model and how do I resolve it.

This is my UserController

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;

class UserController extends BaseController
{
    public function show($id)
    {
        $user = User::findOrFail($id);
        $students = Student::all();
        dd($students);
    }
}

This is my Student model

use App\Models\Course;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'students';

    protected $fillable = [
        'firstname', 'middlename', 'lastname', 'index_no', 'parent_id',
        'regular_or_weekend',
        'course_id',
        'nationality',
        'image'
    ];
}

this is my User model

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'index_no', 'password',
    ];
}

I want to compare student's index_no with the corresponding user's index_no, if they matched then I gets the students detail.

1 like
2 replies
srowden's avatar

Just to be sure, you definitely have rows of data in the 'students' table? An empty collection from Eloquent::all() usually indicates that you don't have anything in the database.

2 likes
tisuchi's avatar
tisuchi
Best Answer
Level 70

There are two ways you can proceed here.

  • Eloquent
  • DB query

Using Eloquent

$students = App\ Student::find($user->id);

Using DB query

$students = \DB::table('students')->find($user->id); 
4 likes

Please or to participate in this conversation.