"Incorrect integer value" when inserting data [Eloquent] - laravel

My controller
$this->validate($request, [
'master_item_id.*' => ['required'],
'quantity.*' => ['required', 'numeric', 'gt:0']
]);
$master_item_id = array_map('intval', $request->master_item_id);
$quantity = array_map('intval', $request->quantity);
$price = MasterItem::whereIn('id',$master_item_id)->get('price');
$transaction = Transaction::create([
'total_price' => 1,
'last_edited_by' => Auth::user()->name
]);
foreach ($master_item_id as $key => $no) {
$input['transaction'] = $transaction->id;
$input['master_item_id'] = $no;
$input['quantity'] = $quantity[$key];
$input['price'] = $price[$key];
TransactionItem::create($input);
}
My model
protected $table = 'transaction_item';
protected $guarded = [];
public $timestamps = false;
public function transaction()
{
return $this->belongsTo(Transaction::class, 'transaction_id');
}
public function item()
{
return $this->belongsTo(MasterItem::class, 'master_item_id');
}
When I create, this error popped up.
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '{"price":1000000}' for column `myDatabase`.`transaction_item`.`price` at row 1
I know the problem is because my $price, but I don't know how to fix this, Is there a better and easier method to fix my problem? Thanks!

Pretty sure the problem is
$input['price'] = $price[$key];
because MasterItem::whereIn('id',$master_item_id)->get('price'); will return something like this:
[{price: X}, {price: Y} ...]
and not something like
[X, Y]
try with this:
$input['price'] = $price[$key]['price'];

Related

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

Single column not being updated in laravel 5

I am tying to update a single column of a table messages and I have the following code:
public function messageSeen(Request $request){
$data = Message::find($request->id);
$success = Message::where('id', $request->id)->update(array('is_seen' => 1));
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?
I tried the other way like the following:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
dd($result->message);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result->message;
$data['user_id'] = $result->user_id;
$data['conversation_id'] = $result->conversation_id;
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
But here I am getting unexpected thing with this method. Here I am being able to do dd($result) and being able to get data like this:
#attributes: array:9 [
"id" => 22
"message" => "How are you?\r\n"
"is_seen" => 0
"deleted_from_sender" => 0
"deleted_from_receiver" => 0
"user_id" => 2
"conversation_id" => 1
"created_at" => "2019-09-29 03:42:39"
"updated_at" => "2019-09-29 03:42:39"
]
however, if I tried to do dd($result->message) then I get null! What am I doing wrong?
I tried the following code:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result[0]['message'];
$data['user_id'] = $result[0]['user_id'];
$data['conversation_id'] = $result[0]['conversation_id'];
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
and it worked but instead of updating it is adding new column when the message is seen. But first I don't understand why do I have to do $result[0]['key'] in the first place.
You need to specify which fields in your table can be mass assigned, by adding or updating the $fillable property of your model:
protected $fillable = [..., 'is_seen', 'message', ...];
This is required for the create() and update() methods, as those accept "mass" variables in the array you pass in. Whereas with save() you have to manually, explicitly, assign the properties on the model, so there is no risk of accidentally saving something you didn't mean to. And this is exactly the behaviour you are seeing - update() is not working, but save() is.
You should try this
public function messageSeen(Request $request) {
$input = Request::all();
$data = Message::find($input['id']);
if (!empty($data)) {
$update = array();
$update['is_seen'] = 1;
$success = Message::where('id', $input['id'])->update($update);
if ($success) {
return response()->json(['status' => 'success'], 200);
} else {
return response()->json(['status' => 'Something went wrong'], 400);
}
} else {
return response()->json(['status' => 'Data not updated'], 404);
}
}
Value depends on data type of is_seen are string or integer

Data not inserted to Mysql using Eloquent laravel

I have problem with insert data to Database table using Eloquent Model insert() method in Larvel. But when I click on submit button then data not inserted in database.
Here is my implemented code:-
Controller
public function receivedAll(Request $request, ItemPR $item_code)
{
$item_code = $request->item_code;
$pr_qty = $request->pr_qty;
$uploadFile = $request->file('file_document');
$update_data = ItemPR::whereIn('item_code', explode(",", $item_code))->update(['receive'=> 'received']);
$get_data = ItemPR::whereIn('item_code', explode(",", $item_code))->orWhereIn('pr_qty', explode(",", $pr_qty))->get();
$data = [];
foreach($get_data as $value) {
if(is_array($uploadFile)) {
foreach($uploadFile as $file) {
$filename = $file->getClientOriginalName();
$folder[] = $file->storeAs('uploads', $filename);
}
$data[] =
[
'item_code' => $value->item_code,
'qty' => $value->pr_qty,
'file_document' => $filename,
'created_at' => Carbon::now(),
'created_by' => Auth::user()->nick_name,
'last_update' => Carbon::now(),
'last_update_by' => Auth::user()->nick_name,
];
}
WarehouseInventory::insert($data);
}
// Model elequent insert
return response()->json(['success'=>"Products Updated successfully."]);
}
Model:- WarehouseInventory.php
class WarehouseInventory extends Model
{
protected $table = 'warehouse_inventori';
protected $primaryKey = 'pr_item';
public $incrementing = false;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'last_update';
protected $fillable = [
'pr_item', 'item_code', 'qty', 'po_number', 'warehouse_id', 'file_document', 'created_at', 'last_update', 'last_update_by', 'created_by'
];
}
Any idea or what's in my code is wrong?
You are using insert() method on eloquent, insert() is the method of DB class, Eloquent has create() method instead,
WarehouseInventory::create($data);
src: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models

Laravel : API response with pagination parameter

I want to pass pagination parameters through POSTMAN and pass sort,order,limits in my model to get query with paginate.? how can i do this? Currently it return error.
Currently my route :
http://localhost:8000/api/allpost
My PostController function :
public function index(Request $request)
{
try {
$allPost = Post::allUserPost();
if($allPost !="" && count($allPost)>0) {
return [
'status_code' => 200,
'message' => "Post retrieved successfully",
'PostDetails' => $allPost,
];
} else {
return response()->json([
'message' => "Post data not found",
'status_code' => 403,
]);
}
} catch (\Exception $ex) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
}
And my POST model function :
public static function allUserPost(Request $request){
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
# code...
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
Currently it returns error
Type error: Too few arguments to function App\Post::allUserPost(), 0 passed in D:\xampp\htdocs\IDM\app\Api\V1\Controllers\Front\PostController.php on line 30 and exactly 1 expected
So how can i pass parameters in postmen and whats the solution for this error?
First change this line to $allPost = Post::allUserPost();
$allPost = Post::allUserPost($request);
and then change this code
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
To
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
and then you can pass these paramets in a query string like
http://localhost:8000/api/allpost?sort=somesort&order=asc&limit=10
Also chage this line
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
to
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
You are missing an argument when calling the allUserPost function inside the try block.
It should be
$allPost = Post::allUserPost($request);
and then you can retrieve the parameters from the $request variable.
Just change this line in your code
$allPost = Post::allUserPost($request);
And then in your function, you have to change your request type. And after that you have to do one more change only use paginate() method not with get() method.
public static function allUserPost(Request $request){
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
I hope this will help you.

Batch insert in codeigniter

Hi I am quite new to cpdeignoter I just wanted to ask if I am doing the insert batch in ci right because it seemed not to work here is my controller
foreach($dat as $key => $val){
$data[] = array('ModelNumber' => $_POST['txt_model_num'][$key],
'Access' => $_POST['txt_accessories'][$key],
'SerialNumber' => $_POST['txt_snum'][$key],
'Charges' => $_POST['txt_charges'][$key],
'OtherRemarks' => $_POST['txt_rem'][$key],
'RequirementID' => $id1);
}
$cmd3 = $this->Software_model->add_type($data);
if($cmd3){
foreach($sql->result_array() as $row){
$id2 = $row['ID'];
}
$data2s = array();
foreach($dat as $key => $val){
$data2s[] = array('EquipmentName' => $_POST['txt_equipb'][$key],
'EquipmentType' => $_POST['txt_equiptype'][$key],
'RequirementID' => $id2);
}
$cmd2 = $this->Software_model->add_equip($data2s);
and this is the model
public function add_type($data)
{
return $this->db->insert_batch('jobtype', $data);
}
public function add_equip($data2s)
{
return $this->db->insert_batch('equipment', $data2s);
}
and the way I duplicate the textboxes in the views is like this
function second function(){
var etype = document.createElement('input');
etype.type = 'text';
etype.setAttribute("name", "txt_equiptype[]");
etype.setAttribute("class", "form-control");
etype.setAttribute("id", "etype");
etype.setAttribute("placeholder", "Enter Equipment Type");
document.getElementById('third').appendChild(etype);
}
thanks in advance
Hope this will help you :
Try out this alternate method :
foreach($dat as $key => $val)
{
$data[$key]['ModelNumber'] = $_POST['txt_model_num'][$key];
$data[$key]['Access'] = $_POST['txt_accessories'][$key];
$data[$key]['SerialNumber'] = $_POST['txt_snum'][$key];
$data[$key]['Charges'] = $_POST['txt_charges'][$key];
$data[$key]['OtherRemarks'] = $_POST['txt_rem'][$key];
$data[$key]['RequirementID'] = $id1;
}
/* Note : remove auto increment primary key from above array if you are including*/
user it for both the foreach

Resources