Save several attributes to the same object in Laravel

3

I have a property table of other properties and created a property_table_table since an property can have several attributes. I have created the models Imovel and Attribute, I need to create an Imovel_atributo model? How could I do in the store method to save multiple attributes on a property?

Model Property:

<?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 Property:

<?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');
}
}
    
asked by anonymous 30.11.2016 / 17:18

1 answer

6
The Many relationship for Many (N:M) for the , it is not mandatory to create model of this relation when it is correctly related using belongsToMany it is simple to insert and delete items in the relationship.

  

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

If you want to, you can even create it, but if it is a relationship that only has the two keys you do not have to, eloquent already has operations in the relationship settings (#.

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');
    }
}

For belongsToMany data in relation a basic example would be:

Insert relationship 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);
}
If your inserir/Remover is namespace in namespace Imovan should be this way too and you put model , note this.

  

How could I do in the App method to save multiple attributes to a store ?

In the request you have to see a imovel of the attributes to be inserted in the property and when saving a array with the explanation put in imovel that attach

$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 minimum example

  

Authors

<?phpnamespaceApp;useIlluminate\Database\Eloquent\Model;classAuthorsextendsModel{protected$table='authors';protected$primaryKey='id';protected$fillable=['name'];public$timestamps=false;publicfunctionbooks(){return$this->belongsToMany('App\Books','booksauthors','authorid','bookid');}}

Books

<?phpnamespaceApp;useIlluminate\Database\Eloquent\Model;classBooksextendsModel{protected$table='books';protected$primaryKey='id';protected$fillable=['title'];public$timestamps=false;publicfunctionauthors(){return$this->belongsToMany('App\Authors','booksauthors','bookid','authorid');}}

Insert/Remove

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

Insertinrelation:

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

Removefromrelationship:

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

References:

30.11.2016 / 20:16