Let’s go to the trivial:
turn the following commands:
php artisan make:model Estado -crm
php artisan make:model Cidade -crm
This way you will make the model, Migration and the 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 set its tables. Run your Migration using the command php artisan migrate
.
Open the model Cidade
and add the following code:
public function Estado()
{
return $this->belongsTo('App\Estado','estado_id');
}
Open the model Estado
and add the following lines:
public function cidades()
{
return $this->hasMany('App\Cidade','estado_id');
}
Now you just need to use the proper tools of the Laravel to make the filters the way you need them:
Example of use applied in Lade:
@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
First of all, welcome to the community. There is simpler way yes, use the models :D I will prepare something for you in a reply, you could post the structure of your tables?
– Alvaro Alves
City id name fk_state
– Mauricio Assis
State id acronym name
– Mauricio Assis
You managed to solve?
– novic