I have a model
Education.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Education extends Model
{
public $timestamps = FALSE;
public function Member(){
return $this->belongsTo('App\Member');
}
}
In database i have a table named educations
In controller when I'm trying to access the data of the educations table through App\Education model I'm getting this error
QueryException in Connection.php line 770: SQLSTATE[42S02]: Base table
or view not found: 1146 Table 'dsse.education' doesn't exist (SQL:
select * from education)
Why laravel is searching for education table in the database where it should search for educations table. What is the problem?
here is the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Member as Member;
use App\Education as Education;
class memberController extends Controller
{
public function addMember(){
$education = Education::all();
var_dump($education);
}
}
Add this to your model. You may set any custom table name as follow
protected $table = 'educations';
I had the same problem before,
and yes it is a solution to add
protected $table = 'educations';
but the problem is because laravel uses a class called
Illuminate\Support\Pluralizer
inside
Illuminate\Support\Str
and this class is not just adding "s" at the end of words or ies...
it is real pluralizer and education is an uncountable word, so is information...
so you need to add $table to your model.
Related
I want to change the default database naming conventions in my Laravel app. By default, Laravel uses snake case for database table and column names. But I want to use Pascal Case for table names and i want to use camel Case for fields.
So a table name of Users instead of users, and field names createdAt, updatedAt, and deletedAt instead of created_at, updated_at, and deleted_at.
I know I can change these on a per-model basis using the $table property but I'd like to change the default without having to modify each model.
Are there any settings like Symfony's NamingStrategy in Laravel?
If you look at the code for Illuminate\Database\Eloquent\Model::getTable() it's pretty straightforward:
public function getTable()
{
return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
}
Same for Illuminate\Database\Eloquent\Concerns\HasTimestamps::getCreatedAtColumn():
public function getCreatedAtColumn()
{
return static::CREATED_AT;
}
So create your own class that extends Model and override that behaviour:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Support\Str;
class Model extends BaseModel
{
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
const DELETED_AT = 'deletedAt';
public function getTable()
{
return $this->table ?? Str::pluralStudly(class_basename($this));
}
}
Now, just have your models extend this class.
You can use stubs for that. Also if you named your table in Pascal Case just use $table property in model which need to be sync with that table.
You can create a new model that you extend your models with.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class ModelWithPascalCase extends Model
{
const DELETED_AT = 'deletedAt';
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
public function getTable()
{
return $this->table ?? Str::pluralStudly(class_basename($this));
}
}
If you want to make Laravel generate your models extending this, you can do it by editing stubs.
Run
artisan stub:publish
then edit stubs/model.stub by replacing Model with your ModelWithPascalCase.
After that, when you run
artisan make:model User
you get your User model extended by ModelWithPascalCase.
Im new to laravel, i am trying to query a specific table in my DB. I only have 1 data table and the standard user auth tables. I am getting a error: BadMethodCallException
Call to undefined method App\Figures::table().
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
}
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Figures;
class figuresController extends Controller
public function figurespag2() {
$dummyDetails = Figures::table('figures')->where('name', 'batman');
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
route
Route::get ( '/pagination2', 'figuresController#figurespag2' );
I know it's going to be something obvious, but I am new to this.
this is wrong
$dummyDetails = Figures::table('figures')->where('name', 'batman');
Method 1---------- laravel eloquent
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
protected $table = 'figures';
}
Controller
$dummyDetails = Figures::where('name', 'batman')->get();
and
Method 2 ---------- laravel Query Builder
$dummyDetails = \DB::table('figures')->where('name', 'batman')->get();
Use this you not need to define table name
public function figurespag2() {
$dummyDetails = Figures::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
First you may need to know laravel model rules.
If you create a table name like "figures" (plural) you need to create its model by Figure (singular).
if you create a table other then this rule then you have to mentioned table name in model like this.
protected $table = "table_name";
you can access table with where condition in controller like this.
public function figurespag2() {
$dummyDetails = Figure::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
Hope this may help you.
I have Author model that looks like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Author extends Model {
public $timestamps = false;
public function role()
{
return $this->hasOne('App\Role');
}
}
And Role model that looks like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
public $timestamps = false;
}
My AuthorController.php looks like:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Author;
class AuthorController extends Controller
{
public function index(){
$role = Author::find(5)->role->pareigos;
return view('authors', ['role' => $role]);
}
}
But I get error like:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column
'roles.author_id' in 'where clause' (SQL: select * from roles where
roles.author_id = 5 and roles.author_id is not null limit 1)
Where does the author_id even come from?
I have two tables in database, first one is authors that has id,firstname,lastname,role_id. Second one is roles that has two rows - id and pareigos. So I use this command:
$role = Author::find(5)->role->pareigos;
To find Author by id (5) and check his role_id in roles table and return pareigos if the ID's matches.
Don't know if I have described the problem clearly - if not, just let me know I eill add more details.
Your relationship is setup incorrectly. The table that has the key pointing to another table, belongs to that other table.
class Author ...
{
public function role()
{
return $this->belongsTo(Role::class);
}
...
This will want to look for a role_id key on authors table. By default, unless you pass more arguments to override it, Laravel uses the calling function name to decide the name of the foreign key for belongsTo relationships. [ method is named role, so it knows to look for role_id ... methodname + _id ]
I have a table named tasks and a model named Task. In my controller method when i run this piece of code
<?php
namespace App\Http\Controllers;
use DB;
//use app\Task;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class Task_Controller extends Controller
{
//
public function decide()
{
if ($input=="show all task")
{
//$rows=DB::table('task')->get();
$rows=\App\Task::all();
foreach($rows as $values)
{
foreach($values as $key=>$val)
echo "$key : $val <br>";
echo "<br><br>";
}
}
}
It gives me following error:
SQLSTATE[HY000]: General error: 1 no such table: tasks (SQL: select * from "tasks")
That is the model should have linked to the task table instead it is linked to the tasks table Why??.
How to make model gets linked to a specific table.
My model class code goes like this
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
//
}
You should name your table tasks, this is the best option.
Another way to fix this is to use $table property:
protected $table = 'task';
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table. You may specify a custom table by defining a table property on your model
https://laravel.com/docs/5.4/eloquent#defining-models
By default, the table name is the plural of the class name. If you want it to point to a different table, then in your model, add
protected $table = 'task';
By default laravel pluralizes the model names to be be the table names unless stated otherwise in the model by.
protected $table = 'task';
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?
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';