Laravel store DB - php

I have a little problem.. When I´m trying to store in a database in laravel it´s show me an error like this
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'usuario' in 'field list' (SQL: insert into `tipificaciones` (`usuario`, `origen`, `estado`, `nombreCliente`, `caso`, `venta`, `palabraClave`, `updated_at`, `fecha`) values (Supervisor, Leads, 1, ssd, 129308jk, 1, sdañldaskñasd, 2020-06-05 10:58:58, 2020-06-05 10:58:58))"
When i see my DB this Column exist, I verify the connection to DB was successfull becouse in another view I return info for another table.
This is my model:
<?php
namespace App\modelo;
use Illuminate\Database\Eloquent\Model;
class TipificacionesModel extends Model
{
protected $table = 'tipificaciones';
protected $fillable = ['id','usuario', 'origen', 'estado', 'nombreCliente', 'caso', 'venta', 'palabraClave'];
const CREATED_AT = 'fecha';
}
And my Controller
public function store(Request $request)
{
TipificacionesModel::create([
'usuario'=>$request['usuario'],
'origen'=>$request['origen'],
'estado'=>$request['estado'],
'nombreCliente'=>$request['nombreCliente'],
'caso'=>$request['caso'],
'venta'=>$request['venta'],
'palabraClave'=>$request['palabraClave'],
]);
return("true");
}
My database
1
How I can fix this
Thanks for colaboration!

Related

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'basic.posts' doesn't exist

When I'm trying to add data to the categories table, it shows an error. This is because I have a database created with the name "basic" and connected with the project.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'basic.posts' doesn't exist
category.php
class Category extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'category_name',
];
}
CategoryController.php
use App\Models\Category;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CategoryController extends Controller
{
public function allcat(){
return view('admin.category.index');
}
public function alladd(Request $request){
$validatedData = $request->validate([
'category_name' => 'required|unique:posts|max:255',
]);
Category::insert([
'category_name'=>$request->category_name,
'user_id'=>Auth::user()->id,
'created_at'=>Carbon::now()
]);
}
}
You have to use Category::create() instead of Category::insert()
Because create() is use for single row insertion and insert() is used for multi-row insertion
And also you don't have to specify created_at timestamps, laravel model handle it
And here you are inerting single row at a time
Category::create([
'category_name'=>$request->category_name,
'user_id'=>Auth::user()->id
]);
Maybe it will helpful

Invalid object name with Many to Many Relationship with 2 DB Connections

I am building a training web application to track associate training and certifications. I have created an Associate model that used a secondary DB connection to another database that has its information generated by another application so I have no control over the structure of the data. The associates table uses the associate's number as primary key and not an auto incremented ID. I have created a table to keep track of every training/certification course that take place. I created a many to many relationship between the Associate and the Course but when trying to add a record to the pivot table I am running an error.
"SQLSTATE[42S02]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'associate_course'. (SQL: insert into [associate_course] ([associate_id], [course_id], [created_at], [updated_at]) values (0000, 1, 2020-01-31 18:36:56.390, 2020-01-31 18:36:56.390))",
Here is the function that is called to create a record in the pivot table (where the error occurs)
public function trained(Course $course, Request $request) {
$request->validate([
'associates' => 'required'
]);
$associates = explode(',', $request->associates);
foreach($associates as $associate_number) {
$associate = Associate::where('NUMBER', $associate_number)->first();
$course->associates()->attach($associate);
}
}
Here is my Associate model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Associate extends Model
{
protected $connection = 'SHOPFLOOR';
protected $table = 'USERS';
public function getRouteKeyName()
{
return 'NUMBER';
}
public function courses()
{
return $this->belongsToMany(Course::class, 'associate_course', 'associate_id', 'course_id', 'NUMBER', 'id')->withTimestamps();
}
}
and here is my Course model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $fillable = ['course_type_id', 'name', 'date', 'expires', 'expires_at', 'notification_threshold'];
public function type() {
return $this->belongsTo(CourseType::class);
}
public function associates() {
return $this->belongsToMany(Associate::class, 'associate_course', 'course_id', 'associate_id', 'id', 'NUMBER')->withTimestamps();
}
}
I tried copying the sql from the error and running it on the database and it does insert the row into the database so that leads me to believe it's something with my Laravel configuration?
Can I get some assistance in fixing this issue?
It's hard to say without seeing your DB structure, Error says clearly that table specified in query is not found. Most probably is that you forgot to specify schema in the statement. IMHO code that you showed is not really related to the problem.
There is a bug with the Laravel sqlsrv driver. I needed to specify the full schema to get it working. In my case this was TRAINING.dbo.associate_course.
So relationships look like this
Associate.php
public function courses()
{
return $this->belongsToMany(Course::class, 'TRAINING.dbo.associate_course', 'associate_id', 'course_id', 'NUMBER', 'id')->withTimestamps();
}
Course.php
public function associates() {
return $this->belongsToMany(Associate::class, 'TRAINING.dbo.associate_course', 'course_id', 'associate_id', 'id', 'NUMBER')->withTimestamps();
}

Eloquent - Having problems using eager loading on nested relationships

I'm trying to eager load nested relationships, but I'm having trouble returning the correct results.
Here are the models:
User.php
class User extends Model
{
public function universities()
{
return $this->hasMany('\StudentApp\Models\UserUniversity');
}
}
UserUniversity.php
class UserUniversity extends Model
{
protected $fillable = [ 'user_id', 'university_id', 'choice' ];
public function university()
{
return $this->hasOne('\StudentApp\Models\University');
}
}
University.php
class University extends Model
{
protected $table = 'university';
}
What I want to do is get a user by ID, fetch the users universities from the UserUniversity pivot table, and then fetch the name of that university from the University table.
I've tried the following to test if it works:
$user = User::with('universities')->find($this->jwtObject->uid);
return $response->withJson($user->universities[0]->university);
But I get the following error:
Column not found: 1054 Unknown column 'university.user_university_id' in 'where clause' (SQL: select * from `university` where `university`.`user_university_id` = 10 and `university`.`user_university_id` is not null limit 1) [] {"uid":"28c5a97"}
user.user_university_id is incorrect. That column doesn't exist and I'm not sure why it's trying to use that column.
What it should be using is user.university_id
How can I do this?
You should add foreign key and primary key in relation:
public function universities()
{
return $this->hasMany('\StudentApp\Models\University', 'university_id', 'id');
}
Correct nested eager loading syntax is:
User::with('universities.university')
Also, make sure you've using the correct foreign key in the university table:
user_university_id
Or define another key in the relationship:
public function university()
{
return $this->hasOne('\StudentApp\Models\University', 'another_foreign_key');
}

Laravel Model renaming MySQL table to plural on query

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';

Laravel : Can not insert data into database

I Have a problem in inserting data into database using eloquent model insertion. I tried
Model->save() and Model::create and it didn't help me ... also i defined fillable Attributes on my model but it didn't work.
Note: I can retrieve data from DB using ::all() or ::find and i can also delete data but i can not insert any data into DB.
My Model Code is:
<?php
class Game extends Eloquent{
protected $table = 'games';
protected $fillable = array('title','year');
}
My Controller Code is:
<?php
class GameController extends BaseController{
public function doit(){
$g= new Game;
$g->title='Xina';
$g->year='2014';
//the error occur here
$g->save();
//also
//Game::create(array('title='Xina','year'='2014'));
//will give an error
}
}
any one could help me? when i tried my code the only error message i got is:
Whoops, looks like something went wrong.
According to your error:
Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into games (title, year, updated_at, created_at) values (Xina, 2014, 2014-12-24 00:03:27, 2014-12-24 00:03:27))
You do not have the Laravel Timestamp columns set on your table.
Stop it checking/setting these columns by setting the timestamps property to false on the model:
$timestamps = false;

Categories