mardi 24 novembre 2015

Laravel - Posting Data to multiple tables with a single form

Let's say I have this form (linked to a named route) that contains 3 text inputs :

{!! Form::open(['route' => 'domain.store'])!!}
{!!  Form::text('srv_prefix',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('srv_ip',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('domain',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::submit('create') !!}

the route calls this function on my controller:

public function store(CreateDomainRequest $request, Domain $domain)
{
    $domain->create($request->all());
    return redirect()->route('domain.index');
}

Always as example, let's say I have 2 tables : domains to store my domains, and servers to store my servers info (1st and second text input) actually I managed to do the inserts on my first table using the controller mentioned above. my question is how can I do the inserts on the 2 tables via a single submit on my form? how to deal with a Request and a controller for each table ?

this is what i did so far :

1 - i have already have 2 related models (Serverand Domain):

Class Server extends Eloquent {
    public function domain(){
    return $this->belongsTo('Domain');
    }
// $fillable and stuff..
}

-

Class Domain extends Eloquent {
    public function servers(){
    return $this->hasMany('Server');
    }
//
}

2 - I'm using eloquent, and my tables are related.

    Schema::table('servers', function($table){
        $table->foreign('id_domain')
            ->references('id_dom')
            ->on('domains')
            ->onDelete('cascade');
    });

The documentation does not show how to insert related models using a form. thanks for your help :)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire