Get latest from different relationship eloquent laravel

Viewed 5580

I have 3 Tables

Model Url

class Url extends Model
{
    public function users(){
        return $this->belongsToMany(User::class);
    }
    public function url_status(){
        return $this->hasMany(UrlStatus::class);
    }
}

Model UrlStatus

class UrlStatus extends Model
{
    public function url()
    {
        return $this->belongsTo(Url::class);
    }
}

Model User

class User extends Authenticatable
{
    use Notifiable, SoftDeletes, HasRoles;
    public function urls(){
        return $this->belongsToMany(Url::class);
    }
}

In my controller I'm querying :

$url = Url::with('url_status','users')->where('list_status', true)->get();

How can I get the latest url_status?

EDIT ---

This is my structure for each table in migration file

FOR URLS TABLE

 Schema::create('urls', function (Blueprint $table) {
            $table->increments('id');
            $table->string('url');
            $table->string('description');
            $table->boolean('list_status');
            $table->timestamps();
        });

URL STATUS

Schema::create('url_status', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('url_id');
            $table->integer('status_code');
            $table->string('status');
            $table->boolean('sms');
            $table->boolean('email');
            $table->timestamps();
        });

USERS TABLE

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('contacts');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
2 Answers

You can try it like this too

Model Url

public function latestUrlStatus(){
    return $this->hasOne(UrlStatus::class)->latest();
}

Fetch it like this

$urls = Url::with('latestUrlStatus','users')->where('list_status', true)->get();
foreach($urls as $url){
    echo $url->latestUrlStatus->status_code;
}

Try to use latest() method with first() like :

$url = Url::with('url_status','users')->where('list_status', true)->whereHas('url_status', function($q){
     $q->latest()->first();
})->get();

If you're trying to get the latest url_status for a given URL it could be done like :

$url->url_status->latest()->first();
Related