Reputation: 3
i have two tables, Student table which have column (id, family_id,name,class,section) Family table which have column (family_id, mobile_no, profession)
-- i have created two models. student model:
class student extends Model
{
}
and family model
class family extends Model
{
public function student()
{
return $this->hasMany('App\student');
}
}
-- i am able to show all data from student table, my controller is:
public function index()
{
$finddata = student::orderBy('id', 'asc')->get();
return view('students.index')->with('finddata', $finddata); }
-- what i tried in family model:
return $this->hasMany('App\students');
what i want;
Upvotes: 0
Views: 1836
Reputation:
You should try this
class student extends Model
{
public function familyId(){
return $this->belongsTo(Family::class,'family_id');
}
}
when you click on student name it will redirect to student/{id}
route
Route::get('student/{id}', 'StudentController@show');
student controller
public function show(Request $request, $id)
{
$student = student::find($id);
return view('student.show')->with('student', $student);
}
student.show.blade file
Mobile no: {{ $student->familyId->mobile_no }}
Profession: {{ $student->familyId->profession }}
Upvotes: 0
Reputation: 1833
In the student model:
class student extends Model
{
public function family(){
return $this->belongsTo(Family::class,'family_id');
}
}
Then you can access family information in Blade by:
{{$student->family->mobile_no}}
{{$student->family->profession}}
You should better use artisan
commands to generate models and controllers, so that you get automatic templates that follow naming conventions, such as uppercase Class names.
Upvotes: 0