Laravel Model renaming MySQL table to plural on query

- 1 answer

Ad

I am using a model to query a remote MySQL DB and when I run the query, Laravel is trying to connect to the plural version of the table that I need it to connect to. The table's name is activity and the error I get is:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'health.activities' doesn't exist (SQL: select * from `activities`)

I just built the model for this using artisan make:model Activity so I am not sure what is going on. Here is my model:

<?php

namespace App;

use DB;
use Role;
use Illuminate\Database\Eloquent\Model;

class Activity extends Model
{
    private $activity;

    function __construct()
    {
        $this->activity = DB::connection('mysql_remote')->table('activity');
    }
}

Here is my controller:

public function getDashboard()
    {
        $data = [
            'page_title' => 'Dashboard',
            'users'      => User::getUser(),
            'test' => Activity::get(),
        ];

        return view('dashboard.dashboard', $data);
    }

Anyone have any idea why this is happening?

Ad

Answer

Ad

Models expect the table to be named the plural of the name of the Model, in this case the plural of Activitiy is activities which is the table name it expects. If it's different, you need to add a table property to set the name of the table.

In your model, add the following...

protected $table = 'activity';
Ad
source: stackoverflow.com
Ad