Home > Net >  How do I insert data in Laravel database from controller?
How do I insert data in Laravel database from controller?

Time:01-22

this is my first post in this forum and also I'm a very new user with Laravel. I'm trying to do a very simple thing like creating an array and visualize the data inside in my database. The code works but I cant see the data in the database table. It might look easy but for some reason I've been a whole day with this thing so I'll appreciate a lot any help I can receive. This is how the code looks right now:

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Client;
use App\Http\Controllers\Controller;

class ClientController extends Controller
{
   public function index()
   {
       DB::table('clients')->insert(
           array(
                  'id'     =>   1, 
                  'name'   =>   'Josh',
                  'age'   =>   45,
                  'gender'   =>   'M',
                  'nationality'   =>   'UK',
                  'job'   =>   'a',
           )
       );
   }

}

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{  
    use HasFactory; 

    protected $fillable = [
        'name', 'age', 'gender', 'nationality', 'job',
    ];

}

Migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('age');
            $table->string('gender');
            $table->string('nationality');
            $table->string('job');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}

CodePudding user response:

First of all in your migration change this line:

 $table->bigIncrements('id');

with

$table->id();

Once you have migrated it with:

php artisan migrate:fresh (empty database and recreate it)

Insert a record with:

public function index()
{
Client::create([
    'name'   =>   'Josh',
    'age'   =>   45,
    'gender'   =>   'M',
    'nationality'   =>   'UK',
    'job'   =>   'a',
]);
}

There is no need to populate the id. Laravel (MySQL) will do it for you.

CodePudding user response:

Maybe you do not need "," at the end of the array

 protected $fillable = [
    'name', 'age', 'gender', 'nationality', 'job',
];
  •  Tags:  
  • Related