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
Related
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'];
How to insert multiple images into the table?
Controller
public function save(Request $request)
{
$images = new Image;
$input = $request->file("image");
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images[]=$name;
$images->Image = $input->getClientOriginalName();
}
}
$images->save();
$image = Image::find($request->id);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
I expect to insert images into database, the the error is No message
I think it's better to use mass assignment to insert your image name into the database. The code will be like this :
public function save(Request $request)
{
$images = new Image;
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images->create(['Image' => $file]);
}
}
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
You must insert it in every loop, if you use the model attribute it will just change every time the loop sets the image name.
public function create(Request $request)
{
$rules = array(
'gallery_album_id'=> 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
);
$input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('images',$name);
$image=$name;
gallery::insert( [
'image'=> $image,
'gallery_album_id' =>$input['gallery_album_name']
]);
}
}
return redirect()->route('gallery')->withStatus(__('Album successfully added.'));
}
how to add points after submitting a post ?
This is my Controller :
public function store(PostRequest $request)
{
$story = Auth::user()->post()->create($request->all());
$image = $request->File('image');
if ($image) {
$image_name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('upload');
$image->move($destinationPath, $image_name);
$story->image = $image_name;
}
$story->update();
if ($story) {
flash()->success('Your Story Has Been successfully added');
}
return redirect()->back();
}
This is my table users :
protected $fillable = [
'name', 'email', 'password', 'point'
];
This is my table post story :
protected $fillable = [
'user_id','title','description','image'
];
It is up to you to implement the logic of when you increment the point field but here is how you can.
$story->increment('point');
Or
$story->point++;
And of course $story->save();
I have two tables Students and Hobbies. I've all details in one form but I want to save details to separate tables on submit. How can I achieve this?
My Student model
<?php
namespace App;
class Students extends Model {
protected $fillable = ['name', 'address'];
public function hobbies() {
return $this->hasMany(Hobby::class);
}
}
Hobby model:
<?php
namespace App;
use App\Product;
class Hobby extends Model
{
protected $fillable = [
'entertainment', 'sports'
];
public function hobby()
{
return $this->belongsTo(Student::class);
}
}
Controller:
public function save(Request $request, Student $student)
{
$students= new Student;
$students->name= request('name');
$students->address= request('address');
$students->save();
if($students->save())
{
$hobbies= [];
$images = $request->file('hob_img');
$hob_desc = $request->hob_desc;
foreach ($request->hob_name as $key => $hobby) {
$hob_img = '';
{
$hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
$files[$key]->move(public_path('/assets/images/'), $hob_img);
}
$hobbies[] = [
'hob_name' => $hobby,
'hob_desc' => $hob_desc[$key],
'hob_img' => $hob_img
];
}
$hobbies[] = new Hobby;
$hobbies->hob_name = request('hob_name')[$key];
$hobbies->hob_desc= request('hob_desc')[$key];
$hobbies->hob_img = request($hob_img)[$key];
$hobbies->save();
}
}
But I cannot save it. It says SQLSTATE[HY000]: General error: 1364 Field 'student_id' doesn't have a default value
Try the insert to save many records at onece :
public function save(Request $request, Student $student)
{
$student= new Student;
$student->name= request('name');
$student->address= request('address');
if($student->save())
{
$hobbies= [];
$images = $request->file('hob_img');
$hob_desc = $request->hob_desc;
foreach ($request->hob_name as $key => $hobby) {
$hob_img = '';
$hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
// $files i think it should be $images
$files[$key]->move(public_path('/assets/images/'), $hob_img);
$hobbies[] = [
'hob_name' => $hobby,
'hob_desc' => $hob_desc[$key],
'hob_img' => $hob_img,
'student_id'=> $student->id
];
}
Hobby::insert($hobbies); // useing Eloquent
// Or you can use Query Builder
// DB::table('hobbies')->insert($hobbies);
}
}
I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}