Reputation: 369
I have created model which name is project
php artisan make:model project
and then using php artisan tinker
tried to add a record into it.
In command line when I run:
$project = new App\project; $project->title='My first project'; $project->save();
It shows this error:
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'title' in 'field list' (SQL: insert into
projects
(title
,updated_at
,created_at
) values (My first project, 2019-01-11 06:46:09, 2019-01-11 06:46:09))'
It doesn't perform $project->save();
and gives this error. Please help.
Upvotes: 1
Views: 4893
Reputation: 454
php artisan make:model project
This is the fault which I believe you do not have a migration file created (refer to Future Reference
section below why I said so), since the error stated that the column is not found.
To better solve this, I suggest you create a migration file as follow:
php artisan make:migration create_projects_table
You can see inside database/migrations
, there is a new file with the name 2019_01_11_153037_create_projects_table
something. The time and date is different from yours, but the main focus is 'create_projects_table'
Inside the migration file, you can see there's up()
function. Copy this code
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
}
Finally, perform a migration, and you should see a migrated success message.
php artisan migrate
In the future, to save time, you can create a model together with its migration, as follow:
php artisan make:model Project -m
Notice the -m
tag, which creates a migration file for you. Afterwards, proceed with editing the migration file (e.g., add columns to it as demonstrated previously).
Learn more about Laravel's migration here: https://laravel.com/docs/5.7/migrations
One additional notes, check out Laravel's convention on Eloquent Model so that Laravel can perform it's magic: https://laravel.com/docs/5.7/eloquent#eloquent-model-conventions
Your project
model should properly be Project
If you have performed a migration somehow before, then run a different migration (there's no limit to how much you can make migration).
php artisan make:migration add_column_title_to_projects_table
And there's a new migration file created. Inside the up()
function, add this code:
public function up()
{
Schema::table('projects', function (Blueprint $table) {
$table->string('title');
});
}
Finally, perform php artisan migrate
Upvotes: 2
Reputation:
You have to try this:
$project = new Project;
$project->title = $request->title;
$project->save(); // it will INSERT a new record
Updated Answer
$project = new App\Project;
$project->title='My first project';
$project->save();
Upvotes: 1