frankhosaka's avatar

Add a record from another table using Eloquent

I'm new in Eloquent. I don't know how use Create, using two tables. So, i improvised.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\tbcontacorrente;
use App\Models\tbdiario;

class DiarioController extends Controller {

public function pagar(Request $request){
    $doctos=tbdiario::select('docto')->where('contad',130)->orWhere('contad',211)
        ->orWhere('contac',130)->orWhere('contac',211)->get()->toArray();
    $pendencias = tbcontacorrente::select('docto')->get()->toArray();
    $a=[];
    foreach($doctos as $key=>$value){$a[]=$value['docto'];} 
    $b=[];
    foreach($pendencias as $key=>$value){$b[]=$value['docto'];}
    $difs=array_diff($a,$b);
    foreach($difs as $dif){
        tbcontacorrente::create(['docto'=>$dif]);}
}
}
0 likes
2 replies
LaryAI's avatar
Level 58

To add a record from another table using Eloquent, you can use the create method on the model for the table you want to add the record to. Here's an example:

$otherRecord = OtherModel::find($id); // get the record from the other table
$newRecord = NewModel::create([
    'field1' => $otherRecord->field1,
    'field2' => $otherRecord->field2,
    // add any other fields you need to populate
]);

In this example, we're getting a record from the OtherModel table using its id, and then creating a new record in the NewModel table using the values from the OtherModel record.

You can modify this example to fit your specific use case. For example, if you want to add a record to tbcontacorrente using values from tbdiario, you could do something like this:

$diarioRecord = tbdiario::find($id); // get the record from tbdiario
tbcontacorrente::create([
    'docto' => $diarioRecord->docto,
    // add any other fields you need to populate
]);

This would create a new record in tbcontacorrente using the docto value from the tbdiario record.

webrobert's avatar

I don’t follow. FYI there is a free series here on laravel. Laravel 8 from scratch

Please or to participate in this conversation.