Laravel : Can not insert data into database - php

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;

Related

Laravel store DB

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!

Base table or view not found in laravel 5.3

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.

Laravel 5.1 (Eloquent) in using relationship attaching or detaching not working

I'm having problems in using Laravel 5.1's Eloquent. I have 2 databases, and 2 model classes are using a different database (that is not default database).
It is working well for simple CRUD, but when I use relationship, it causes an error.
$list->users()->attach($nListUser->id, [
'entered' => $user->createdDate,
'modified' => date('Y-m-d H:m:s'),
]);
Or
$list->users()->detach($nListUser->id);
Error code is
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'sampledb.listuser' doesn't exist (SQL: insert
into listuser (entered, listid, modified, userid)
values (2012-06-17 18:34:58, 52275, 2016-01-18 02:01:46, 6))
This is my model class file.
class ListUser extends Model
{
protected $connection = 'listdbconnection';
protected $table = 'listuser';
public $timestamps = false;
}
class PList extends Model
{
protected $connection = 'listdbconnection';
protected $table = 'list';
public $timestamps = false;
public function users(){
return $this->belongsToMany('App\Model\User', 'listuser', 'userid', 'listid');
}
}
Eventhough I set connection name above, it is still finding the table in default database. It is clear that the Eloquent is working on default database for relationship.
Has anyone solution for this? Am I wrong or Is this really Laravel 5.1 Eloquent's fault?
Finally found the reason.
Eloquent was wonderful. The model class I specified in the belongsToMany parameter was wrong.
It was actually, as belows.
return $this->belongsToMany('App\Model\LUser', 'listuser', 'userid', 'listid');
I recommend Eloquent because you can use it outside Laravel. Maybe, good choice for web service development.

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 Eloquent ORM - save() returns column not found (MySQL error)

The issue I'm running into is that I want to save the model, but I have a method call which writes to the instance and for some reason Laravel is trying to update that column.
Club Model (relevant code):
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Club extends Eloquent
{
use SoftDeletingTrait;
protected $table = 'clubs';
protected $fillable = array('name', 'address', 'city', 'state', 'zip', 'contact_name', 'contact_email', 'contact_phone', 'contact_photo', 'club_code', 'logo');
public function getCurrentCampaign($id = 0)
{
if (!$id)
{
if ($this->currentCampaign)
{
return $this->currentCampaign;
}
$id = $this->id;
}
$now = date('Y-m-d H:i:s');
$this->currentCampaign = DB::table('campaigns')
->where('club_id', $id)
->where('start_date', '<=', $now)
->where('end_date', '>=', $now)
->pluck('id');
return $this->currentCampaign;
}
}
The issue exists on the "club settings" page where a user can edit some stuff - I have a few updates that run on different tables, and then later I use $club->save(). I found that even if I call it directly after getCurrentCampaign, it throws the error.
$club = Club::findOrFail($clubID);
$club->getCurrentCampaign();
$club->save(); // Error
Error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currentCampaign' in 'field list' (SQL: updateclubssetupdated_at= 2014-07-08 12:49:17,currentCampaign= 27 whereid= 23)
Considering that currentCampaign isn't in the $fillable array, I don't know what's happening. Am I misunderstanding how that works?
Thanks
Edit: For clarity, there are a few different things loaded into $club, not just the campaigns. I'm simply giving one for illustrative purposes.
Anything that you save on the Model object that is NOT a property would be treated as an attribute/table column. To avoid this you can simply declare those properties on the model:
// Club model
public $currentCampaign;
Then using your code won't cause the error you experience now.
Anyway, probably you should consider #watcher's suggestion on working with relations instead, but that depends on your app.
And about the fillable array - it has nothing to do with saving data but rather with filling object with an array of data (mass assignement):
$model->fill($someArray);
this is called when you __construct new object, save or update providing an array etc.
I don't think you're specifying your campaign relationship in 'the laravel way'. The underlying issue is that you're adding a property to your model, and, during saving, Eloquent believes that extra non-standard property represents a column in your database so it is trying to save it as such.
This is the path I'd take to solve it:
public function campaigns()
{
// 'hasMany' may not be what you need, just guessing
// from what I see so far...
return $this->hasMany('Campaigns');
}
public function currentCampaigns($now)
{
return $this->campaigns
->where('start_date', '>', $now)
->where('end_date', '<', $now);
}
Now, given an instance of a 'club', you can get its current campaigns like this:
$club->currentCampaigns(date('Y-m-d H:i:s'));
The relationship above is determined by how you structure the relationship in the database.
If your club table has a 'campaign_id' field, then the relationship in the club model to the campaign model would be belongsTo.
If there is a third table that has both campaign ids and club ids in it and thats how you determine what clubs are related to what campaigns, that relationship is hasMany
I belive also if you have a campaign_id in your clubs table, it will need to be present in the fillable array in order to actually be able to set it.

Categories