A
A
Andrew2020-09-12 21:38:22
Laravel
Andrew, 2020-09-12 21:38:22

How to get value from linked table in Eloquent?

Hello... I'm using Laravel for the first time and I still don't quite understand how to do the following:
1. get data from the table related to the relationship (city name)
2. add this name to the output
3. specify in the query that to display data from the table with the value "any ".

Controller code:

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Animal;
use App\User;
use App\City;
//пропущен стандартный код 
    public function showAll()
    {
        $data = Animal::where([ ['need_home',1], 
                                ['need_help',0], 
                                ['isDone',0],
                                ['city_id',  55],  //из модели City нужно получить name города и
// как-то добавить его к данным вывода return к каждому объекту массива.
                                ['kind', '*'] //звездочка не работает. Как указать "выводи с любым значением?"    
                                ])
                                ->latest()
                                ->get(['id', 'name', 'age', 'image', 'city_id', 'author_id']);
        return $data;
    }


belongsTo('Cities');

Help if anyone knows. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-09-12
@jazzus

If each Animal has one city, then in the Animal model

public function city()
{
  return $this->hasOne(City::class);
}

Request
Animal::with('city')
           ->...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question