Tower
Tower

Reputation: 345

How to use Laravel DB to fetch data from dynamically created tables?

I have been creating an application in Laravel 5.3 and because of the nature of the application, I needed to create a table specific to each user that registers. To do so I have used the homeController (user is redirected to it after a successful registration) and this code is used in it :

$user_id = Auth::user()->id;
$user_name = Auth::user()->name;
$table_name = $user_name . '_' . $user_id;

if (Schema::hasTable($table_name))
{   
    $specs = DB::table($table_name)->select('select * from ' . $table_name);
    return view('home')->with('rvalue', $specs);
}else{      
    Schema::connection('mysql')->create($table_name, function ($table){
        $value = 0;
        $table->string('address')->default($value);
        $table->string('phone')->default($value);
        $table->string('name')->default($value);
    });
}


As of the code in home.blade.php I've added :

foreach ($rvalue as $value)
{
    var_dump($value);
}

My problem is that although the table and the columns in it are created and present in the database, I still don't know how to retrieve the default value that is assigned to the columns at the time of their creation and send and display them in the view.
I would be very thankful of you if you could tell me how to make it work.

Upvotes: 0

Views: 1536

Answers (1)

astratyandmitry
astratyandmitry

Reputation: 515

Your query to database must be like this:

DB::table($table_name)->select('*')->get();

Select method used to specified selected fields, not for query it self.

Read official documentation for more useful methods: https://laravel.com/docs/5.3/queries

Upvotes: 1

Related Questions