php - Laravel - query from database and save to another

785

Welcome! I try to find a solution for my problem but it's hard for fresh laravel user. I try to do some simple booking system. I have 2 tables: schedule, and bids. What I want to do is display schedule table and via "book" button save it to bids table. I know how to query schedule table but I don't know how to write controller to save same data to another table.

Regards and thank you for the help.

860

Answer

Solution:

You can do it in in the same controller class by adding a new function inside it. Here is the sample code.

class YourController extends Controller
{

public function bookSchedule()
{
    //here we are getting the data from the table
    $s = Schedule::where('id','=',98)
                ->select('colomn_1','colomn_2')
                ->get()
                ->toArray();
    // here we are storing it back to the bids table
    Bids::insert($s);
}

Hope the answer has helped you.

934

Answer

Solution:

first of all you should show some examples of what have you done,

also your database connection file

however you should connect the 2 databases inapp/config/database.php like the following

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

and then in the controller you can chose which database you are talking to for example$users = DB::connection('mysql2')->select(...);

check the Laravel Documents

People are also looking for solutions to the problem: php - Laravel: method to set the value of a custom primary key

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.