Reputation: 11
I'm creating an app using laravel. Tables and columns will be created on the frontend applying the schema codes inside the controller. But how can I do to create models without programming each one manually? Any idea to code it?
Controller example (is working fine):
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class teste extends Controller
{
public function CreateTable(Request $tableName)
{
Schema::create($tableName, function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
//return view
}
}
Upvotes: 1
Views: 853
Reputation: 868
You can use this to create models from your controller.
Artisan::call('make:model ' + $modelPath + '/' + $request->modelName)
Now there are a lot of options to create migrations, controller, resource routes etc. along with the model. You can check them out if you want.
The command will create the model. You can create the model from the table name of course. But it will not follow the naming conventions. Like table names are in plural and model name are in singular form with the first letter in upper case.
If you had used artisan
to create the table migration along with model Laravel would've handled some complex namings. Like Category
model with categories
table, or Software
model with software
table. That's why I recommend sending the model name separately from your view.
The real problem arises when you plan to build a whole model programmatically along with the fields. Laravel does not allow you to do that. You would have to build a custom command to handle this.
Also, even if you make the fields programmatically, you'd still have to go back to the model to define the relations. You can build your custom command to handle this too.
However, you can go through this question to have some idea. This guy asked for a similar thing like you.
Also, there are some packages that read your table and backtrack it to build your model. Here's an example. Another example here.
Note: if you plan on building your custom command and make it open-source please let me know.
Upvotes: 1