1

I have a question about how to structure the code the right way when I add data to related tables.

I have this, and it works. But is that the correct way? Seems a bit messy

Relations tables:

Property:

public function up()
    {
        Schema::create('imoveis', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tipoImovel_id');
            $table->string('finalidade',20);
            $table->string('titulo',100);
            $table->date('data')->nullable();
            $table->integer('concelho_id');
            $table->string('freguesia',50);
            $table->string('rua',150);
            $table->decimal('long', 10, 7)->nullable();
            $table->decimal('lat', 10, 7)->nullable();
            $table->boolean('destaque');
            $table->boolean('estado')->default(true);
            $table->string('descricao',500);
            $table->string('preco',40);
            $table->integer('empresa_id')->default(1);
            $table->timestamps();
        });

House:

public function up()
    {
        Schema::create('moradias', function (Blueprint $table) {
            $table->integer('imovel_id');
            $table->integer('nrPisosConstrucao');
            $table->integer('nrQuartos');
            $table->integer('nrWcs');
            $table->integer('areaConstrucao');
            $table->integer('areaTerreno');
            $table->smallInteger('anoConstrucao');
            $table->timestamps();
        });

Photos

 Schema::create('fotos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('imovel_id');
            $table->string('nome',15);
            $table->timestamps();
        });

And to insert a House i have that function in HouseController, and works... but seem kind a messy...

public function create(){

        //save Property(BASE)
        $this->imovel->titulo = Input::get('titulo');
        $this->imovel->finalidade = Input::get('finalidade');
        $this->imovel->data =  Input::get('data');
        $this->imovel->concelho_id = Input::get('concelho');
        $this->imovel->freguesia = Input::get('freguesia');
        $this->imovel->rua = Input::get('rua');
        $this->imovel->long = Input::get('longitude');
        $this->imovel->lat = Input::get('latitude');
        $this->imovel->descricao = Input::get('descricao');
        $this->imovel->preco = Input::get('preco');
        $this->imovel->tipoimovel_id = 1; //Empresa- 
        $this->imovel->save();

        //save House
        $moradia= new Moradia;
        $moradia->imovel_id = $this->imovel->id;
        $moradia->nrQuartos = Input::get('nrQuartos');
        $moradia->nrPisosConstrucao = Input::get('nrPisos');
        $moradia->nrWcs = Input::get('nrWcs');
        $moradia->areaConstrucao = Input::get('areaConstrucao');
        $moradia->areaTerreno = Input::get('areaTerreno');
        $moradia->anoConstrucao = Input::get('anoConstrucao');
        $moradia->save();

        //upload photos
          $files = Input::file('images');
          $contaFotos=0;

           foreach ($files as $file) {
            $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
            $validator = Validator::make(array('file'=> $file), $rules);
            if($validator->passes()){
             $extension = $file->getClientOriginalExtension();
              $destinationPath = 'uploads';  //folder 
              $filename = $this->imovel->id . '_'. $contaFotos++ . '.' . $extension;
              $upload_success = $file->move($destinationPath, $filename);

              // SAVE DB
              $extension = $file->getClientOriginalExtension();   
              $foto= new Foto();
              $foto->imovel_id = $this->imovel->id;
              $foto->nome = $filename;
              $this->imovel->fotos()->save($foto);
            }
          }

          return view('admin.imoveis.index');


    }

Models Relation in Property

public function atributos(){
    //se for moradia
    if ($this->tipoimovel_id == 1) {
        return $this->hasOne(Moradia::class);
    }
    //se for apartamento
    else if ($this->tipoimovel_id == 2) {
        return $this->hasOne(Apartamento::class);
    }
    //se for loja
    else if ($this->tipoimovel_id == 3) {
        return $this->hasOne(Loja::class);
    }
    //se for armazem
    else if ($this->tipoimovel_id == 4) {
        return $this->hasOne(Armazem::class);
    }
    //se for terreno para construção
    else if ($this->tipoimovel_id == 5) {
        return $this->hasOne(TerrenoConstrucao::class);
    }
    // se for terreno para outros fins
    else if ($this->tipoimovel_id == 6) {
        return $this->hasOne(TerrenoOutrosFins::class);
    }
2
  • 1
    It's correct by all means, but there are nicer way to do some things. Validation is usually put in requests. You could attach attributes with $this->imovel->fill(Input::all()) method (you'll have to deal with mass assignement though). Your migrations are great though. Depending on version you're using not all of these might apply though. Which version are you using? Commented Mar 15, 2017 at 19:41
  • last version of laravel. but i have more types os property, like apartment, shop. I have to do same thing in ApartmentConstroller and ShopController? Commented Mar 15, 2017 at 19:44

1 Answer 1

1

It basically depends on your relationships, The following way works both for one to many and one to one.

    $moradia= new Moradia;
    //Removed insertion for id from here.
    $moradia->nrQuartos = Input::get('nrQuartos');
    $moradia->nrPisosConstrucao = Input::get('nrPisos');
    $moradia->nrWcs = Input::get('nrWcs');
    $moradia->areaConstrucao = Input::get('areaConstrucao');
    $moradia->areaTerreno = Input::get('areaTerreno');
    $moradia->anoConstrucao = Input::get('anoConstrucao');
    // This is what i added
    $this->imovel->atributos() -> save($moradia);

And same is the case for image.

Sign up to request clarification or add additional context in comments.

9 Comments

use atributos() in $moradia->atributos()->save($moradia);
Edited the answer, I added () to atributos so now its atributos().
instead of $moradia->relationShipName->save($moradia); should be $imovel->relationShipName->save($moradia); or $this->imovel->relationShipName->save($moradia);?
It will be $moradia->atributos()->save($moradia);.
give me an error Call to undefined method Illuminate\Database\Query\Builder::atributos()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.