SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' - php

I am beginner in Laravel 7, I am using two tables 'empmast' and 'empatten'. I displayed the values of empmast (empid, empname) and joined two fields (empstatus, doa) with same. Then I tried to push these values to 'empatten' table. The thing is these values are trying to save in the empmast instaed empatten table. Kindly assist.
Complete Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' in 'field list'
(SQL: insert into `empmast` (`empid`, `empname`, `empstatus`, `doa`, `updated_at`, `created_at`) values (2, Kirupa Shankar, Present, 17-05-2020, 2020-05-17 06:34:26, 2020-05-17 06:34:26))
EmpAttenController:
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request, Empatten $empatten)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}
Empatten(Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Empatten extends Model
{
protected $fillable = [
'empid' => 'array',
'empname' => 'array',
'empstatus' => 'array',
'doa'
];
}

Create new instance of your model before you try to save
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten = new Empatten(); // initiate your model class
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}

Related

Laravel hasMany error. 'site_id' doesn't have a default value

I have following method in a controller
public function store(Request $request)
{
$site = Site::create([
"path" => $request->path,
"site_link" => $request->link,
]);
if ($request->features) {
$features = explode(',', $request->features);
foreach ($features as $feature) {
$site->features()->save(SiteFeature::create(["feature" => $feature]));
}
}
return response()->json($site, 201);
}
Site model has this method
public function features()
{
return $this->hasMany('App\SiteFeature');
}
And this is my $fillable property of a SiteFeature
protected $fillable = ['feature', 'site_id'];
By some reason I get next error
local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'site_id'
doesn't have a default value (SQL: insert into site_features
(feature) values (fes)) {"exception":"[object]
(Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]:
General error: 1364 Field 'site_id' doesn't have a default value (SQL:
insert into site_features (feature) values (fes))
The Model::create method actually creates a record in your database and since you're not specifying a required site_id, it is failing which is why you're seeing this error.
It looks like you're trying to use Laravel's relationships to save a new SiteFeature for the site but you're passing what would be an already existing object (if the query didn't fail) to the relation's save method.
You need to either pass a new instance of SiteFeature, that has not already been saved to the database to the save method:
$this->features()->save(new SiteFeature(['feature' => $feature]));
or you can use the relation's create method to avoid having to pass in an instance altogether, you just need to provide the attributes:
$this->features()->create(['feature' => $feature]);
try this
in your model features
public function features()
{
return $this->hasMany('App\SiteFeature','site_id','id');
}
you model SiteFeature
public function siteFeatures()
{
return $this->belongsTo('App\features', 'site_id', 'id');
}
$site = Site::create([
"path" => $request->path,
"site_link" => $request->link,
]);
Doesn't return the last insert id... try
$site = new Site;
$site->path = $request->path;
$site->site_link = $request->link;
$site->save();
As for this part:
if ($request->features) {
$features = explode(',', $request->features);
foreach ($features as $feature) {
$site->features()->save(SiteFeature::create(["feature" => $feature]));
}
}
You could do this if the above code doesnt work...
if ($request->features) {
$features = explode(',', $request->features);
foreach ($features as $feature) {
$sf = new SiteFeature;
$sf->feature = $feature;
$sf->site_id = $site->id;
$sf->save();
}
}

Has many through update / with pivot laravel 5.5

I have several tables (all of them with created_at, updated_at, deleted_at) :
sectors
lang_sector
valuechains
lang_valuechain
segments
lang_segment
keyneeds
keyneed_lang
the tables are linked in this order :
sectors has many valuechains
valuechains has many segments
segments has many keyneeds
Here is my model :
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Sector extends Model
{
use SoftDeletes;
protected $table = "sectors";
protected $fillable = ['admin_id'];
protected $dates = [ 'created_at', 'updated_at', 'deleted_at' ];
public function langs() {
return $this->belongsToMany('App\Lang')
->withPivot('sectname', 'sectshortname', 'segname_slug',
'sectdescription', 'sectshortdescription'
)
->withTimestamps();
}
public function admin()
{
return $this->belongsTo('App\Admin');
}
public function valuechains()
{
return $this->hasMany('App\Valuechain');
}
public function segments()
{
return $this->hasManyThrough('App\Segment', 'App\Valuechain');
}
public function keyneeds()
{
return $this->hasManyThrough('App\Keyneed', 'App\Segment', 'App\Valuechain');
}
}
In my destroy controller :
public function destroy($id)
{
$sector = Sector::findOrFail($id);
$sector_ids = $sector->langs()->allRelatedIds();
foreach ($sector_ids as $id){
$sector->langs()->updateExistingPivot($id, ['lang_sector.deleted_at' => Carbon::now()]);
}
$sector->valuechains()->update( [ 'valuechains.deleted_at' => Carbon::now() ] );
$sector->segments()->update( [ 'segments.deleted_at' => Carbon::now() ] );
$sector->keyneeds()->update( [ 'keyneeds.deleted_at' => Carbon::now() ] );
Sector::where('id', $id)->delete();
return redirect()->route('sectors.index')->with('success', 'Sector deleted');
}
My issue is that it doesn't update the following tables : segments and keyneeds (which have created_at, updated_at and deleted_at fields) and their pivot tables too ... And that i have an error message :
SQLSTATE[23000]: Integrity constraint violation: 1052 Field: 'updated_at' in field list is ambiguous (SQL: update segments inner join valuechains on valuechains.id = segments.valuechain_id set segments.deleted_at = 2018-05-10 06:54:54, updated_at = 2018-05-10 06:54:54 where valuechains.sector_id = 2)
it adds : updated_at
I succesfully updated :
sectors table
valuechains table
lang_valuechain pivot
My issue is to update
segments table by using : $sector->segments()
keyneeds table by using : $sector->keyneeds()
And their pivot table as well... I read the documentation but it doesn't help.
I use the update() method because $sector->segments()->delete() is trying to make a hard delete...
I finally find an issue to this.. Not very elegant but it's working on the "main" tables. I'll have to solve the little problem on pivot tables :
public function destroy($id)
{
$sector = Sector::findOrFail($id);
$valuechains = Valuechain::where('sector_id','=',$sector->id)->get();
foreach ($valuechains as $valuechain) {
$segments = Segment::where('valuechain_id', '=', $valuechain->id )->get();
$valuechain->langs()->updateExistingPivot($valuechain->id, ['lang_valuechain.deleted_at' => Carbon::now()]);
foreach ($segments as $segment) {
$keyneeds = Keyneed::where('segment_id', '=', $segment->id)->get();
$segment->langs()->updateExistingPivot($segment->id, ['lang_segment.deleted_at' => Carbon::now()]);
$segment->delete();
foreach ($keyneeds as $keyneed) {
$keyneed->langs()->updateExistingPivot($keyneed->id, ['keyneed_lang.deleted_at' => Carbon::now()]);
$keyneed->delete();
}
}
$valuechain->delete();
}
$sector->langs()->updateExistingPivot($id, ['lang_sector.deleted_at' => Carbon::now()]);
$sector->delete();
return redirect()->route('sectors.index')->with('success', 'Secteur suppprimé');
}

Array to string conversion (SQL: insert into

I'm trying to insert data from a Seeder in Laravel 5.6 and I'm having a problem with the field that is json type. I want this field ('stops') to be an array (for example of ten integers not repeated).
The table seeder (RoutesTableSeeder.php) is something like this:
<?php
use \Illuminate\Support\Facades\DB;
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Models\Route;
class RoutesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//factory(Route::class, 20)->create();
$faker = Faker::create();
//$values= array();
/*for($i=0; $i < 10; $i++) {
$values []= $faker->unique()->randomDigit;
}
print_r(json_encode($values));*/
foreach (range(1, 20) as $index)
{
$values = array();
for($i=0; $i < 10; $i++) {
$values []= $faker->unique()->randomDigit;
}
//print_r($values);
DB::table('routes')->insert([
'user_id' => $faker->numberBetween($min = 1, $max = 20),
'name' => $faker->name,
'description' => $faker->name,
'route_photo' => $faker->image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null),
'stops'=> [
//$values,
json_encode($values)
//implode(", ", $values)
],
]);
}
}
}
I tried several ways to insert data. When I use json_encode($values) I have the following error:
Array to string conversion
(SQL: insert into `routes` (`user_id`, `name`, `description`, `route_photo`, `stops`)
values (19, Isaac
Feil, Holly Nolan, /tmp/bc8a3cf5e015d3afa96317485499e0ca.jpg,
[8,6,0,7,3,1,5,2,4,9]))
This kind of value [8,6,0,7,3,1,5,2,4,9] is what I want to store in 'stops' field, for example, but I don't know what is going wrong....
Please, would you be so kind to help me? I'm desperate....
I post the model if it helps:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Route extends Model
{
protected $fillable = [
'user_id',
'name',
'description',
'route_photo',
'stops'
];
protected $casts = [
'stops' => 'array'
];
}
And the migration:
public function up()
{
Schema::create('routes', function (Blueprint $table) {
$table->increments('id');
//FK:users
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
//FK:users
$table->string('name');
$table->string('description')->nullable();
$table->string('route_photo');
$table->json('stops');
$table->timestamps();
});
}
Thanks a lot!!
json_encode($values) returns a string, which you can use as the value of the stops column. There's no need to put [] around it, that creates an array, and you can't store an array directly into a column. Just leave out the brackets:
'stops' => json_encode($values)
However, storing arrays in database columns is generally a bad idea, it violates normalization principles. You should use a separate table with a row for each value.
Don't cast stops to array, First remove
protected $casts = [
'stops' => 'array'
];
And use json_encode to make string
'stops'=> json_encode($values),

Laravel 5 collection issue: Where not equal to

I am currently working on a modal where a user can insert an excel file. The task of the system is to upload and/or add a new database record if the records are new or identical to what exists in the database. BUT it also needs a delete function for getting rid of those records where the slug column is not identical to the name column.
At the moment I am using Laravel 5.3, and this is my controller as it is now:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Input;
use Maatwebsite\Excel\Facades\Excel;
class ProductsController extends Controller {
public function importExcel(Request $request) {
if (Input::hasFile('productFile')) {
$path = Input::file('productFile')->getRealPath();
$checkbox = Input::get('productCheckbox');
$data = Excel::load($path, function($reader) {
})->get();
if (!empty($data) && $data->count()) {
foreach ($data as $key => $value) {
$product = Product::all()->where('slug', $value->slug)->first();
$product_false = Product::all()->where('slug', '!=' , 'name')->get();
if ($product_false !== null){
//delete row if slug does not matches name
dd($product_false);
}
The dd above returns all products, so the collection query is not working properly (see below for the raw SQL that I am trying to run in this collection)
if ($product !== null) {
//update row if exist
$product->name = $value->name;
$product->description = $value->description;
$product->price = $value->price;
$product->save();
} else {
//add new row if not exist
$product = new Product;
$product->slug = $value->slug;
$product->name = $value->name;
$product->description = $value->description;
$product->price = $value->price;
$product->save();
}
}
header("Location: /products");
}
}
}
}
This is the Product model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'slug', 'name', 'description', 'price',
];
}
Here is the PHPMyAdmin raw SQL (which works) that I basically am looking for to use in the collection:
SELECT * FROM `products` WHERE `slug` != `name`
I hope someone can help me out from this pit. I have been sailing the waves of the internet for about 12 hours now just to get this done.
~ nitsuJ
Collections, eloquent and query builder are not the same. Collection provide a bunch of methods to work on arrays, rather then on the database or model.
In collection context whereNot() is not available.
but the same function can be achieved through whereNotIn('key', [value])
collect([
[
'name' => 'foo',
'rank' => 2
],[
'name' => 'bar',
'rank' => 3
],[
'name' => 'foobar',
'rank' => 4
],
])->whereNotIn('rank', [4])
same as where rank not in (4)
Change
$product = Product::all()->where('slug', $value->slug)->first();
$product_false = Product::all()->where('slug', '!=' , 'name')->get();
Into
$product = Product::where('slug', $value->slug)->first();
$product_false = Product::where('slug', '!=' , 'name')->get();
Try this
$product = Product::where('slug', $value->slug)->first();
$product_false = Product::whereRaw('slug != name')->get();
Simple where won't work as it compares products.slug with "name"(string).
I managed to solve it.
$data = Excel::load($path, function($reader) {
$importedSlugs = $data->select(array('slug'))->toArray();
//collection of imported slugs
$collectionOfImportedSlugs = collect($importedSlugs)->flatten()->all();
//get all product slugs
$productSlugs = Product::all()->pluck('slug');
//get all different slugs!
$diffSlugsArray = $productSlugs->diff($collectionOfImportedSlugs)->all();
//dd($diffSlugsArray);
foreach ($diffSlugsArray as $diffSlug) {
$product_false = Product::all()->where('slug', $diffSlug)->first();
echo $product_false->slug . 'has been deleted!';
$product_false->delete();
}
})->get();

Laravel 5.2 MongoDB & MySQL in Same App Error

I have a MongoDB connection & MySQL Connection details setup in my config/database.php file. I can connect to the MongoDB Details and get a response but when i try connect to the MySQL database, i get the following error:
FatalThrowableError in Builder.php line 1514:
Call to a member function compileSelect() on null
I've tried the solutions from this page:
Issue with Out of the box Laravel Authentication but none of the solutions have worked.
I'm not using any authentication on the app, just querying a MySQL database to return data.
[Updated]
Route link from app/Http/routes.php
Route::get('v1/{showdata}/{name}', 'ShowDataController#percentData');
Controller: ShowDataController.php
namespace App\Http\Controllers;
use App\ShowData;
use App\MongoDataPull;
class ShowDataController extends BaseController
{
public function percentData($showdata, $name)
{
$showdata;
$name;
$signupsremaining = 0;
//Percentage Calculator
if ((ShowData::where('name', '=', $name)->first()) === null) {
// If not found, change status to Not Listed
$percentagetakeup = 'Not Listed';
} else {
// If found, Run Percentage Calculator
$totalrequired = ShowData::select('total_required')->where('name', '=', $name)->value('total_required');
$currentinterest = ShowData::select('current_interest')->where('name', '=', $name)->value('current_interest');
$percentagetakeup = round((($currentinterest) / $totalrequired) * 100);
// Calcualte the number of signups remaining for the fibrehood.
$signupsremaining = $totalrequired - ($currentinterest);
if ($signupsremaining < 0) {
$signupsremaining = 0;
} else {
$signupsremaining = $signupsremaining;
}
}
return ['percentagetakeup' => $percentagetakeup, 'signupsremaining' => $signupsremaining];
}
}
From ShowData Model ShowData.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ShowData extends Model
{
protected $table='qualify';
protected $fillable=[
'id',
'name',
'total_required',
'current_interest',
'status'
];
}

Categories