Skip to content

Instantly share code, notes, and snippets.

@multiarts
Last active January 4, 2018 04:45
Show Gist options
  • Save multiarts/4f807426e32e889c9cccfb749aef399a to your computer and use it in GitHub Desktop.
Save multiarts/4f807426e32e889c9cccfb749aef399a to your computer and use it in GitHub Desktop.
/*
table client:
id
bairros_id
name
Table bairros
id
name
*/
class Client extends Model
{
public function bairros()
{
return $this->belongsTo(Bairros::class);
}
}
// ClientController
public function show($id)
{
$cat = Client::where('id', $id)->firstOrFail();
return response()->json($cat->bairros); // Aqui o bairros_id quero que ele exiba o nome do bairro
}
@andreisena
Copy link

andreisena commented Jan 4, 2018

A tabela client deveria ser clients

Na tabela clients o campo de relacionamento com a tabela bairros deveria ser bairro_id

Troca o nome do relacionamento na linha 14 para bairro:

public function bairro()

O nome model deve estar sempre no singular, só a tabela no plural, veja na linha 16 deveria ser Bairro::class

Nas linha 23 e 24:

$cat = Client::with('bairro')->findOrFail($id);
return response()->json($cat);

@Wpkenpachi
Copy link

Wpkenpachi commented Jan 4, 2018

Vai no Model Client -> Provavelmente está em App\Client.php.
Adicione um método à esta classe...
// Client

public function bairro(){
    return $this->hasOne( 'App\Bairro' , 'id', 'bairros_id'); 
}

Agora no seu controller

// ClientController
public function show($id)
{
	$cat = Client::with(['bairro' => function($bmodel){
              $bmodel->select('id', 'nome')->get();
        }])->where('id', $id)->firstOrFail();

	return response()->json($cat->bairros); 
}

@multiarts
Copy link
Author

@Wpkenpachi, retornou o mesmo resultado.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment