Answer the question
In order to leave comments, you need to log in
Laravel how to properly set up communication?
There are two tables. First city:
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->uniqid();
$table->string('name');
$table->integer('order');
$table->timestamps();
});
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->uniqid();
$table->string('name');
$table->integer('cities_id')->unsigned()->index()->nullable();
$table->foreign('cities_id')->references('id')->on('cities');
$table->timestamps();
});
class City extends Model
{
protected $fillable = ['slug', 'name', 'order'];
public function player(){
return $this->hasMany('App\Player');
}
}
class Player extends Model
{
public function city(){
return $this->belongsTo('App\City');
}
}
<template>
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Slug</td>
<td>Имя</td>
<td>Город</td>
</tr>
</thead>
<tbody>
<tr v-for="player,index in players">
<td>{{ player.id }}</td>
<td>{{ player.slug }}</td>
<td>{{ player.name }}</td>
<td>{{ player.cities_id }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data(){
return{
players: [],
}
},
created: function()
{
this.fetchPlayers();
},
methods: {
fetchPlayers()
{
let uri = '/admin/player';
this.axios.get(uri).then((response) => {
this.players = response.data;
});
}
}
}
</script>
Answer the question
In order to leave comments, you need to log in
You need to make a Laravel Resource
for the Player model and for City
using
In the files, write the fields that you want to get in json (id, name, etc.)
Then go to PlayerResource and connect the relationship resource in the header
Next, you add a relationship field to the Player:
public function toArray($request)
{
return [
// поля модели, которые нужно отдалть в json
'id' => $this->id,
'name' => $this->name,
// Отношения
'cities' => CityResource::collection($this->cities),
'city' => new CityResource($this->city)
];
}
public function getPlayers()
{
$players = Player::with('cities')->get();
return PlayerResource::collection($players);
}
Who is the cutest in the world?
All blush and whiter?
That's right, docks! https://laravel.com/docs/5.7/eloquent-serialization
PS More specifically, in your case, this section: https://laravel.com/docs/5.7/eloquent-serializatio...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question