Insert data to Mysql about Viewers Laravel

Viewed 48

Have some question.

I need table with data about my visitors. I have This Schema :

public function up()
    {
        Schema::create('viewers', function (Blueprint $table) {
            $table->increments('id')->primary('id');
            $table->string('ip_address', 45)->nullable();
            $table->string('country')->nullable();
            $table->string('city')->nullable();
            $table->text('device')->nullable();
            $table->timestamp('last_activity')->useCurrent();
            $table->rememberToken();
        });
    }

That's my Controller in my page.

public function index(Request $request)
{

    $viewer = New Viewers();

    $data = \Stevebauman\Location\Facades\Location::get('83.143.245.162');

    $viewer->ip_address = $request->ip();
    $viewer->country = $data->countryName;
    $viewer->city = $data->cityName;
    $viewer->device = $request->userAgent();

    $viewer->save();
}

That's my Error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into `viewers` (`ip_address`, `country`, `city`, `device`, `updated_at`, `created_at`) values (::1, Germany, Frankfurt am Main, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Safari/605.1.15, 2020-11-26 10:11:06, 2020-11-26 10:11:06))

Why updated_at, created_at trying to inserting into table??

3 Answers

By default all models on laravel has updated_at and created_at. If your table dont have it you should disable it by adding public $timestamps = false; on the model.

class Viewers extends Model
{
   public $timestamps = false;

It's default Laravel feature, Laravel would try to automatically fill in created_at/updated_at and wouldn’t find them.

If you do not want those two column in your Viewers model, add following line.

 public $timestamps = FALSE;  

You are missing $table->timestamps() in your migration

public function up()
{
    Schema::create('viewers', function (Blueprint $table) {
        $table->increments('id')->primary('id');
        $table->string('ip_address', 45)->nullable();
        $table->string('country')->nullable();
        $table->string('city')->nullable();
        $table->text('device')->nullable();
        $table->timestamp('last_activity')->useCurrent();
        $table->rememberToken();
        $table->timestamps();    //for created_at and updated_at columns
    });
}

And if you don't want updated_at and created_at columns

class Viewer extends Model
{
//In Model class set timestamps to false
    public $timestamps = false;
}
Related