Quang BGT
Quang BGT

Reputation: 1

Laravel: two models in one controller method

Let me explain about my problem. I am currently using Laravel 5.0. Here is my structure

Now I want to do these:

Everytimes creating new item into bgts table, I want to make a copy and insert into bgthistories table. Then, everytimes that record is updated, i'll copy one more version, still insert into bgthistories.

Here is store() method.

public function store(Request $request) {
    $bgt = new Bgt();
    $history = $this->coppy($bgt);
    $uploader = new UploadController('/data/uploads/bgt');
    $bgt->name = $request['name'];
    $bgt->avatar = $uploader->avatar($request);
    $bgt->attachments($uploader->attachments($request));
    //dd($bgt);
    $bgt->save();
    $history->save();
    return redirect('bgt');
}

And this is the coping:

public function coppy($bgt) {

        $array = $this->$bgt->toArray();

        $version = new BgtHistory();
        foreach($array as $key => $value) {
            $version->$key = $value;
        }

        return $version;
    }

I create migration tables already. Everything is ready. But, when I call

 $bgt->save();
 $history->save();

It did not work. If I remove $history->save();, it create new record ok. I think the save() method that built-in in Model provided by Laravel is problem. Can anyone tell me how to solve this.

I tried to build the raw query then executed it by DB:statement but it did not work too. Every try to execute anything with DB is failing.

Upvotes: 0

Views: 776

Answers (1)

Kyslik
Kyslik

Reputation: 8385

Please research before re-inventing the wheel.

(Same stuff different sites in case one is down)

http://packalyst.com/packages/package/mpociot/versionable

https://packagist.org/packages/mpociot/versionable

https://github.com/mpociot/versionable

Cheers and good luck ;)

Upvotes: 1

Related Questions