How can I change Laravel SQL Table Query? - php

My Laravel User Table name is s_user but result is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'laravel_learn.users' doesn't exist (SQL: select * from users where
users.id = 1 limit 1) (View:
C:\xampp\htdocs\nawabpur1\resources\views\frontend.blade.php)
Please help me! how can i change users table. my table name is s_user but laravel query result show users but why? how can i change it users to s_user?

Since you have not defined that what the table name is, Eloquent automatically, searches for snake cased plural form of your model's name, in this case users, furthermore, as it can not locate it, you get that error.
So to edit it, within the app\User.php file, which is your User model, set the $table property.
For your other question, which you have posted as an answer as how to change the primary key field, Eloquent assumes you have an primary column named as id, to change it, set it within the $primaryKey variable.
class User extends Model
{
// Define table name explicitly
protected $table = 's_user';
// Define primary key explicitly
protected $primaryKey = 'user_id';
}
All of those information are written in the Laravel documentation, do not forget it, check it out.

Related

Laravel sends SQL request to the wrong table without reason

I have a problem with Laravel, let me describe all steps.
Created migration "create_user_role_table" with:
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
Created Role and UserRole models
In UserRole model:
protected $table = "user_role";
protected $guarded = false;
In Role and User models added function belongsToMany.
IndexController: $user = User::find(1); dd($user->role[0]->title);
After those steps, laravel without reason trying to open "role_user" table, not "user_role". Where did he find this table in the code? "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'blog.role_user' doesn't exist". If rename table in DataBase to "role_user", it's work. How to solve that, where did he found table with name "role_user"?
Laravel's naming convention for pivot tables is snake_cased model names in alphabetical order separated by an underscore. So, if one model is User, and the other model is Role, the pivot table will be role_user.
You are free to use any table name you want (such as user_role), but you will then need to specify the name of the pivot table in the relationship. This is done using the second parameter to the belongsToMany() function.
return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id');

How laravel defines a related table to a model that will be executed to get some data? [duplicate]

I am curious about how eloquent knows in which table it should save the records we give it by running $ php artisan tinker . I do not actually remember setting so an option.
In Laravel when using Eloquent you should assign a table name using the property $table for example:
protected $table = 'some_thing';
Otherwise it assumes that the table name is the plural form of the model name and in this case for User model the table name should be users. Follwing paragraph is taken from Laravel website:
Table Names
Note that we did not tell Eloquent which table to use for our Flight
model. 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 use this instead:
class Flight extends Model
{
// Explicit table name example
protected $table = 'my_flights';
}
So, if you don't follw this convention when creating/naming your database tables that Laravel expects then you have to tell Laravel the name of the table for a model using a protected $table property in your model.
Read the documentation here.
Actually if you not set the $table property, Eloquent will automatically look the snake case and plural name of the class name. For example if class name is User, it will users.
Here the code taken from Illuminate/Database/Eloquent/Model.php
public function getTable()
{
if (isset($this->table)) {
return $this->table;
}
return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
}
Model name is mapped to the plural of table name, like User model maps to users table and so.
When you do
User::all() laravel knows that you want the records from users table.
To specify the table name explicitly you use protected $table ='name' field on model.
Actually, Eloquent in its default way, is an Active Record System just like Ruby On Rails has. Here Eloquent is extended by a model. Those model name can be anything starts with capital letter. Like for example User or Stock
but the funny thing is this active record system will imagine that if no other name of custom table is specified within the class model then the table name should be the small cased plural form of the Model name. In these cases users and stocks.
But by keeping aside theses names you can extensively can provide your own table name within the model. As in Laravel protected $table= 'customTableName'
Or, in a more descriptive way,
class Stock extends Eloquent{
// Custom Table Name
protected $table = 'custom_tables';
}
I hope this will solve your curious mind.

Disable Laravel Pluralization For Person To People

I have a table called agency_persons with some data already in it. I created a model using php artisan:
php artisan make:model AgencyPerson
Now when I try to use Laravel's Eloquent methods i face following error:
Base table or view not found: 1146 Table
'my_database.agency_people' doesn't
Laravel is looking for people table instead of persons.
I know Laravel is trying to do the right thing and I should have named my table agency_people in the first place, but I cannot change name of the table, because other applications are using this table too.
How can I disable laravel's pluralization for person to people?
In the model, add the line
protected $table = 'agency_persons';
See https://laravel.com/docs/5.5/eloquent for more details, look for section Tablenames
If you are using persons table and person model in laravel. Laravel Pluralization For Person To People will give you this error whatever your query would be:-
Base table or view not found: 1146 Table 'lrv_db.people' doesn't exist (SQL: select `posts`.*, `people`.`country_id` from `posts` inner join `people` on `people`.`id` = `posts`.`person_id` where `people`.`country_id` = 1)'
Solution for this is :-
Define your table in the person model as below:
class person extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'persons';
}
You can also define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model.
Example:
protected $fillable = ['title', 'description'];
Once you have made the attributes mass assignable, you can use the create method to insert a new record in the database.
The use of $fillable to protect which fields you want this to actually allow for updating.

Laravel Create Model Class with tables that has a schema

i have a very simple question that somehow it might sound stupid but excuse me . I am working on a project where i use sql server with an existing database where table names are having a schema , forexample dob.Tablename . My question is , if i want to create eloquent model for Tablename , how will i name my class ?
Create new model and add table property:
protected $table = 'existing_table_name';
Just be named the table name removing s corresponding to elequent model name.For example:- Elequent model name User then your database table name is users.

Laravel sounds like magic

I just recently started experimenting with laravel, lovely. One thing l dont understand though is how laravel knows my table l just added a model and the model isnt the exact table name, but just how does it manage to get my table,
Reference to Eloquent Model Conventions:
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.
Internally, Laravel does something like this.
$table = $table ?: Str::plural($name);
So it will automatically try to look for the plural of your model name if no $table property is being set.
Laravel follows a Naming convention for Eloquent Classes and Tables.
From Laravel Website | Eloquent: Getting Started
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.
Eg.
Class User will by default refers to Mysql Table users (Camel Case to Snake Case and Plural).
Class NotificationsLog will by default refers to Mysql Table notifications_logs (Camel Case to Snake Case and Plural).
But if you don't want to follow the convention then you can Mention the table name explicitly
Eg.
If I want my Class Plane should refers to flights table in Database then following code will work
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plane extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'flights';
}
Actually the when you make a model it automatically make a table with it's plural you could change this by added the following code in the model
protected $table= 'table_name';
Please also check the name in the migration it should be same as the name you mentioned in the model class because it might show error while using eloquent class functions due to different table names

Categories