Let's go to the trivial:
run the following commands:
php artisan make:model Estado -crm
php artisan make:model Cidade -crm
In this way you will make the model, migration and controller in just one command
You will have the following migrations:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEstadosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('estados', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nome',500);
$table->string('sigla',2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('estados');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCidadesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cidades', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('estado_id')->unsigned();
$table->string('nome',500);
$table->foreign('estado_id')->references('id')->on('estados')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cidades');
}
}
This way you have already referenced the foreign key and defined its tables. Run your migration using the php artisan migrate
command.
Open the model Cidade
and add the following code:
public function Estado()
{
return $this->belongsTo('App\Estado','estado_id');
}
Open the Estado
model and add the following lines:
public function cidades()
{
return $this->hasMany('App\Cidade','estado_id');
}
Now you just need to use laravel's own tools to do the filters the way you need them:
Use example applied to blade:
@foreach($estados as $estado)
<tr>
<td class='sua_classe_para_diferenciar'>{{$estado->nome}}</td>
</tr>
@foreach($estado->cidades as $cidade)
<tr>
<td>{{$cidade->nome}}</td>
</tr>
@endforeach
@endforeach