Home > Net >  Laravel Eloquent Query Building ORM
Laravel Eloquent Query Building ORM

Time:06-01

Let's assume, There Is two Table 'student' & 'state', 'student' table contain 'id', 'name', 'state_id'. and 'state' table contain 'id', 'state_name'. In 'student' table contain the corresponding State ID.

Now I want to fetch the student's details including the state name. (Note: In the student table, I contain only the state id) How can I achieve this?

CodePudding user response:

Maybe this helps you:

Students.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Student extends Model
{
    use HasFactory;

    protected $fillable = ["id", "name", "state_id"];

    public function state()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

StudentController.php

public function show($id)
{
    $student = Student::where('id', $id)->with('state')->get();
}

CodePudding user response:

Try this

In your student model

public function state()
{
    return $this->belongsTo(State::class, 'state_id');
}

now you can fetch student details with the state

public function show($id)
{
    $student = Student::with('state')->find($id);

    //for access the state name
    //$student->state->state_name
}

CodePudding user response:

Student Modal

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    public function state()
    {
        return $this->belongsTo( State::class );
    }
}

Get Students With State

$students = Student::query()->with( 'state' )->get()

Search Students By State Name

$state = 'Dhaka';

$students = Student::query()->whereHas( 'state', function ( $query ) use ( $state ) {
    $query->where( 'state_name', 'like', "%{$state}%" );
} )->paginate( 10 );
  • Related