-1

I have this query

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif')
   ->distinct()
   ->get();

And I want to insert the information of this query in a new table in my database

How could I do that? somebody can help me?

  • Does this answer your question? [Laravel eloquent insert data with multiple relationship](https://stackoverflow.com/questions/57031129/laravel-eloquent-insert-data-with-multiple-relationship) – jkruskie Jan 10 '20 at 20:06

5 Answers5

0

You can create a new instance of a model, append the data, and then save it. You can use relationships to join the data to the other table.

Example:

$user = new User();
$user->name = "Not set";
$user->email = $email;
$user->password = NULL;
$user->save();

$accounts = new Account();
$accounts->email = $email;
$user->account()->save($accounts);

$userAccount = new UserAccount();
$userAccount->userAccount()->sync([
   $user->id,
   $accounts->id

Laravel Relationships: https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models

Laravel Queries: https://laravel.com/docs/5.8/queries#inserts

jkruskie
  • 412
  • 4
  • 15
0

You have the data from the first table so you're almost there. Based on the current format you can loop through it and insert() into the new table.

Some pseudo-code:

foreach ($data as $inData) {
    DB::table('some_new_table')->insert(['column1' => $inData->column1, 'column2' => $inData->column2, ...]);
}
Matt K
  • 6,620
  • 3
  • 38
  • 60
  • I did like this: public function index() { $data = DB::table('incidencias') ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif') ->select('incidencias.rif') ->distinct() ->get(); return view('ATC.index', compact('data')); foreach ($data as $inData) { DB::table('clientes_view') ->insert(['rif' => $inData->rif]); } } but didn't fill the table in my database... how could I fix it... THanks!! – Laravel Oscar Jan 13 '20 at 03:35
0

You can create a view in your database for this situation. create a migration and in up method write your sql, and it will fill automaticely by your database.

  public function up()
  {
    DB::statement("
      CREATE VIEW clients_view AS
      (
         // wirte your sql command here
      )
    ");
  }
Farid shahidi
  • 318
  • 4
  • 9
0

You can insert the data like this

DB::table('table')->insert($data);

Insert accept arrays

0
 public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required'
        ]);
        $category = new Category();
        $category->name = $request->name;
        $category->slug = str_slug($request->name);
        $category->save();
        Toastr::success('Category Successfully Saved','Success');
        return redirect()->route('admin.category.index');
    }