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
}
@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