Save multiple attributes to the same object in Laravel

Asked

Viewed 1,794 times

4

I have an immovable table other of attributes and created an immovel_attribute table since an immovable can have several attributes. I created the models Immovel and Attribute, need to create a model Immovel_attribute? How could you do in the store method to save several attributes in an immovable?

Model Imovel:

<?php

namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
protected $fillable = [
    'nome', 'disponivel_venda', 'valor_venda', 'disponivel_locacao', 'valor_locacao', 'descricao', 'observacao', 'dormitorios', 'garagens', 'area_util', 'area_total', 'novo', 'comercial', 'lancamento', 'cep', 'endereco', 'numero', 'complemento', 'bairro', 'cidade', 'estado', 'condominio', 'nome_condominio', 'fotos',
];

public function attribute()
{
    return $this->belongsTo('App\Attribute');
}

public function type()
{
    return $this->belongsTo('App\Type');
}

public function owner()
{
    return $this->hasOne('App\Owner');
}
}

Model Attribute:

<?php

namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
protected $fillable = [
    'nome',
];

public function property()
{
    return $this->hasMany('App\Property');
}

}

Controller Imovel:

<?php

namespace Imovan\Http\Controllers;
use Imovan\Property;
use Imovan\Type;
use Imovan\Attribute;
use Imovan\Owner;
use Imovan\Http\Requests\PropertyRequest;

class PropertyController extends Controller
{
public function __construct()
{
    $this->middleware('auth');
    $types = Type::all(); //Passa variaveis para todas as views
    view()->share(compact('types')); //Passa variaveis para todas as views
    $attributes = Attribute::all();
    view()->share(compact('attributes'));
    $owners = Owner::all();
    view()->share(compact('owners'));
    $properties = Property::all();
    view()->share(compact('properties'));
}
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $properties = Property::all();
    return view('/property/index')->with('properties', $properties);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('/property/create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(PropertyRequest $request)
{
    $params = $request->all();
    $property = new Property($params);
    $property->save();
    return redirect()->action('PropertyController@index');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $property = Property::find($id);
    return view('/property/edit')->with('property', $property);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(PropertyRequest $request, $id)
{
    $params = $request->all();
    $property = Property::find($id);
    $property->update($params);
    return redirect()->action('PropertyController@index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $property = Property::find($id);
    $property->delete();
    return redirect()->action('PropertyController@index');
}
}

1 answer

7


Relationship Laravel N:M

The relationship Many for Many (N:M) to the , is not obligatory the creation of model of that relationship when it relates correctly using belongsToMany it is simple to insert and delete items in the relationship.

I created the models Imovel and Atributo, need to create a model Imovel_atributo?

If you want you can create, but, if it is a relationship that only has the two keys has no need, the already have the operations in the relation settings (belongsToMany), now if this table has several fields is a case to think about so it all depends on the scenario but basically has no need.

In your specific case configure:

<?php namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
    protected $fillable = ['nome'];

    public function property()
    {
        return $this->hasMany('Imovan\Property');
    }

    public function imovel()
    {
        return $this->belongsToMany('Imovan\Imovel',
                                    'imovel_atributo', 
                                    'attribute_id', 
                                    'imovel_id');
    }

}

<?php namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
    protected $fillable = [
        'nome', 'disponivel_venda', 
        'valor_venda', 'disponivel_locacao', 
        'valor_locacao', 'descricao', 'observacao', 
        'dormitorios', 'garagens', 'area_util', 'area_total', 
        'novo', 'comercial', 'lancamento', 'cep', 'endereco', 
        'numero', 'complemento', 'bairro', 'cidade', 'estado', 
        'condominio', 'nome_condominio', 'fotos'];

    public function attribute()
    {
        return $this->belongsToMany('Imovan\Attribute',
                                    'imovel_atributo',
                                    'imovel_id',
                                    'attribute_id');
    }

    public function type()
    {
        return $this->belongsTo('Imovan\Type');
    }

    public function owner()
    {
        return $this->hasOne('Imovan\Owner');
    }
}

To inserir/Remover data in relation a basic example would be:

Insert relation item:

$a = Attribute::find(1);
$b = Property::find(1);
if ($a)
{
   $a->Property()->attach($b->id);
}

Remove item from relation:

$a = Attribute::find(1);
$b = Property::find(1);
if ($a)
{
   $a->Property()->detach($b->id);
}

Observing: If your namespace is namespace Imovan us model it should be like this and you put App, notice this.

How could I do in the method store to save several attributes in a imovel?

In the requisition will have to come a array of the attributes to be inserted in immovable and when to save a imovel with the explanation put in the attach that array

$b = Property::find(1);
$b->attribute()->attach([array_do_atribute]);
//se for numa edição de registro pode utilizar sync no lugar attach
//tem a funcionalidade de verificar os que são inseridos e remover o que não
//fazem parte do array.

A minimal example

inserir a descrição da imagem aqui


Authors

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authors extends Model
{

    protected $table      = 'authors';    
    protected $primaryKey = 'id';    
    protected $fillable   = ['name'];    
    public  $timestamps   = false;

    public function books()
    {        
        return $this->belongsToMany('App\Books',
                                    'booksauthors',
                                    'authorid',
                                    'bookid');
    }
}

Books

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Books extends Model
{    
    protected $table      = 'books';
    protected $primaryKey = 'id';
    protected $fillable   = ['title'];
    public  $timestamps   = false;
    public function authors()
    {        
        return $this->belongsToMany('App\Authors', 
                                    'booksauthors', 
                                    'bookid',
                                    'authorid');
    }
}

Insert/Remove

$a = Authors::find(2);
$b = Books::find(2);

Insert into the relationship:

$a->books()->attach($b1);
//ou
$a->books()->attach($b->id);

Remove from the interface:

$a->books()->detach($b);
//ou
$a->books()->detach($b->id);

References:

  • I made the changes to the models and am passing the array to the controller store method, but I didn’t understand how to save. I also didn’t understand why of use of find().

  • If you followed the examples, if you passed the array in the method store and then gave a attach to save in the relationship, it is because managed to save, you have to check in the database. When I saw your question I realized that the doubt was a little bigger, so I put a minimal example. The find has the purpose of fetching an item from your bank if it is satisfactory you can save the relations as is in the reply and this is an example. In case store is generating a new property after saving use $propery->attribute()->attach([1,2]); to save to relation. Any doubt post 1 comment

  • I was able to save the immovable id in the database with 2 attribute ids, but I chose 3 attributes: $Property->attribute()->attach([1,2])?

  • @Marcelo ai que tá, as you are sending, this is a screen with checkbox for example and when selecting send together the information of the property ... What would your screen look like? Perhaps a new question would be better because it is explains you the process as it works recording and removing many for many in Eloquent.

  • I’m using a select to send data to the controller: <select name="attributes[]" Multiple="Multiple" class="form-control"> @foreach($Attributes as $value) <option value="{$value->id}}">{{$value->name}</option> @endforeach </select>

  • @Marcelo just assign $b = Property::find(1); $b->attribute()->attach($request->input('atributos', []);

  • 1

    It worked, thank you.

  • I don’t know if I should open a new topic for this, but regarding the editing of attributes I use the Sync method like this: public Function Edit($id) { $Property = Property::find($id); $Property->attribute($id)->Sync([]); Return view('/Property/Edit')->with('Property',; }

  • @Marcelo open another question and correlate with this. and something else is like this line of code: $property->attribute()->sync([1,2,3]);

  • 1

    I will open another. Regarding the line that posed my problem is that I do not know the amount of attributes that will exist because the user who will register.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.