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.
Dec 7, 2019
2
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.
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.