#12 CRUD - CREATE functionality | Laravel 5 6
Created by Imran Sayed Last updated January, 2020 English
Database Commands for Terminal. ( Querybuilder Vs Eloquent method )
Note: You can use querybuilder methods like DB::table…. without creating a model, howeverIn order for you to use the Eloquent methods like \App\modelname::all() then you need to create a model for that database first like so :
php artisan make:model Modelname
To create a Table follow two steps:
# Step 1: Create Migration Table
php artisan make:migration filename --create=tablename # Creates a table inside database/migrations dir
e.g. php artisan make:migration create_my_songs_table --create=songs
# Step 2: Migrate/Create the database table
php artisan migrate
TO UPDATE AN EXISTING PRE MIGRATED TABLE AFTER ADDING NEW FUNCTIONS
php artisan migrate:refresh // https://laravel.com/docs/5.0/migrations
#Basic Insert/Update/Delete Operations
php artisan tinker
a-Insert Data
# Insert
DB::insert('insert into tablename (id, name) values (?, ?)', [1, 'Dayle']);
or
DB::table('tablename')->insert(['title'=>'Closer', 'artist'=>'chainsmoker', 'created_at'=>new DateTime, 'updated_at'=>new DateTime]);
or
# Lets say the model name is Post.php and tablename is posts.
$post = new App\post(); // will create an instance of App\modelname so that you dont have to type App\modelname again
$post->title = 'First post'; // will insert the title column value in posts table after doing $post->save();
$post->body = 'this is body'; // // will insert the body column value in posts table after doing $post->save();
$post->save();