I have laravel project with vouchers table
this is the structure of the vouchers table
Schema::create('vouchers', function (Blueprint $table) {
$table->increments('id');
$table->string('voucher_number',25)->unique();
$table->integer('voucher_dealer');
$table->date('voucher_date');
$table->integer('voucher_customer_id');
$table->double('voucher_amount');
$table->text('voucher_note');
$table->integer('voucher_type');
$table->integer('voucher_inserter');
$table->timestamps();
$table->softDeletes();
});
And the model name is Voucher
Now when i need to get customer voucher i use this relation
public function CustomerReportGet(Request $request)
{
$full = Voucher::where('voucher_customer_id','=',$request->customer_id)->sum('voucher_amount');
if($request->from_date == '' and $request->to_date == '')
$data = Voucher::where('voucher_customer_id','=',$request->customer_id)->get();
elseif($request->from_date <> '' or $request->to_date <> '')
{
$data = Voucher::where('voucher_customer_id','=',$request->customer_id)->
whereBetween('created_at',array($request->from_date,$request->to_date));
}
return array($full,$data);
}
And i have them as ajax request in the blade page
now my problem is that when i create the report
its should be like this ..
customer id
voucher date
voucher amount
customer balance till the voucher date
how can i let laravel always sum the voucher_amount till every voucher_date in the blade
thanks
Try the following:
public function CustomerReportGet(Request $request)
{
$full = Voucher::where('voucher_customer_id','=',$request->customer_id);
if($request->from_date == '' and $request->to_date == '')
$full->sum('voucher_amount')->get();
elseif($request->from_date <> '' or $request->to_date <> '')
{
$full->whereBetween('created_at',array($request->from_date,$request->to_date))->sum('voucher_amount')->get();
}
return array($full,$data);
}
Related
I have 1 table data . and I have function edit on this table . in this edit form I have select dropdown to show pluck from database .
I have 3 table . this name is aduan, ipsrs , teknisi
struckture aduan table
id
user_id
ipsrs_id
teknisi_id
aduan
etc.....
ipsrs table
id
nama_bagian
etc....
teknisi table
id
ipsrs_id
nama_teknisi
etc...
This is my controller :
public function index(Request $request)
{
$ipsrs = DB::table('ipsrs')->pluck('nama_bagian','id');
$belum_kerjakan = Aduan::with('users')->where('status','Belum Dikerjakan')->get();
$teknisi = Teknisi::where('ipsrs_id' , 1)->pluck('nama_teknisi', 'id');
$dalam_proses = Aduan::with('users')->where('status','Sedang Dikerjakan')->get();
$selesai = Aduan::with('users')->where('status','Selesai')->get();
return view('admin.admin_dashboard',[
'belum_dikerjakan' => $belum_kerjakan,
'dalam_proses' => $dalam_proses,
'selesai' => $selesai,
'ipsrs' => $ipsrs,
'teknisi' => $teknisi,
]);
}
Example this variable $belum_dikerjakan is showing table data and I have fucntion edit on this table ( in modal) .
But this I don't know how to catch data (ipsrs_id) to set where clause in the pluck . I want to change 1 to ipsrs_id form table , but how ?
If I understood the problem then here is the answer
pull only the ids from ipsrs table and pass to Teknisi table whereIn method
$ipsrsIds = DB::table('ipsrs')->pluck('id')->toArray();
$teknisi = Teknisi::whereIn('ipsrs_id' , $ipsrsIds)->pluck('nama_teknisi', 'id');
public function edit($id)
{
$category =Category::findOfFail($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}
In Migration Table:
Schema::create('passws', function (Blueprint $table) {
$table->increments('id');
$table->integer('regist_id')->unsigned()->nullable();
$table->foreign('regist_id')->references('id')->on('regists');
$table->string('age');
$table->timestamps();
});
}
Regist Model - Mass Assignment Defined.
public function pass(){
return $this->hasOne('App\Passw');
}
In Controller
$name = $request->name;
$task = Regist::whereName($name)->get();
foreach ($task as $tasks){
$passw1->regist_id = $tasks->id;
}
$passw1->age = $request->age;
$regist = new Regist();
$regist->pass()->save($passw1);
When i store data, only age is getting stored but regist_id stored as null, (no error message or nothing). Here i'm sure controller shows "regist_id" => 1 and "age" => 25 when i use dd($passw1); regist_id is only not getting stores in DB table.
Where am i doing an error??
Try this
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
If you have more than one Regist for $name then try this
$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model
foreach ($regists as $regist){
$regist->pass()->create([
'age' => $request->age
]);
}
Check document here https://laravel.com/docs/5.6/eloquent-relationships#the-create-method
How can I reduce the number of stock in laravel?
In my products table i have stock column where i set numbers of item i have and i want to reduce it in 2 conditions:
1- when is added to order table (not when the product is in user cart)
2- when the order status is not cancelled (if order status become cancelled stocks increase back)
PS: currently I have no code for this matter that's why i didn't share
any code, I'm seeking for idea of how done it. Base on that i will
make functions and share here to complete it.
JSON of Order
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":1,\"attributes\":[{\"attr\":{\"label\":\"Gray\",\"price\":\"7000.00\"}}],\"conditions\":[]},{\"id\":27,\"name\":\"new product\",\"price\":7246,\"quantity\":2,\"attributes\":[],\"conditions\":[]}]"
UPDATE
base on #btl answer I added code below in my order model:
protected static function boot()
{
parent::boot();
$productIdsAndQuantities = $this->products->map(function ($product) {
return [$product->id => $product->quantity];
});
static::updating(function (Order $order) {
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
I think this code needs fix in $productIdsAndQuantities and $product->update(['stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)]); parts before i can use it.
currently i get error below when i try to add my cart detail to orders table
Using $this when not in object context
UPDATE 2
I changed my code to:
protected static function boot()
{
parent::boot();
static::updating(function (Order $order) {
$productIdsAndQuantities = $order->product_name->map(function ($product) {
return [$product->id => $product->quantity];
});
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
now my order will be placed but nothing changes on stock column.
any idea?
Your tables look like,
Product
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
......
$table->integer('stock');
$table->timestamps();
});
Stock
Schema::create('stocks', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('order_id')->unsigned();
$table->enum('fall_rise',[-1,1]);
$table->timestamps();
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('order_id')->references('id')->on('orders');
});
orders
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
.....
.....
$table->timestamps();
});
Now, add a sample product with stock value 10 like
$product = new Product();
$product->name = "abc";
......
$product->stock = 10;
$product->save();
Now, when abc is ordered, add details in order table. Now, stock value to be decreased then update value of stock column in product by 10-1 = 9, add record in stocks table like
Sample values,
product_id = 1;
order_id = 1;
....
fall_rise = -1;
In this way, when 10 stocks of the product are ordered then stock column becomes zero and hence product becomes unavailable. If you want to fetch only available products then use query like,
$available_products = Product::where('stock', '>', 0)->get();
I hope you will understand.
Register model events to handle updates on orders.
In your Order model:
protected static function boot()
{
parent::boot();
static::updating(function (Order $order) {
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id');
if ($oldStatus->name !== 'cancelled' && $order->orderstatus->name === 'cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update(['stock' => $stock + $product->order->getAttribute('quantity_of_product_ordered')]);
});
}
// added to order table similar to above...
// check if it's a new product id being added to the order, decrease stock quantity accordingly...
// ...
});
}
SOLVED
the trick was to use try { on my CartController when I wanted to save my data in orders table there I should place my codes like:
try {
$order = new Order();
$qty = Cart::getTotalQuantity();
$order->product_data = $cartItems;
$order->user_id = Auth::user()->id;
// rest of it...
Auth::user()->orders()->save($order);
//trick is in this part
foreach ($cartItems as $item) {
$product = Product::find($item->id);
$product->decrement('stock', $item->quantity);
}
the answer was provided here
I'm trying to edit a column of datatable to show informations in my index view table.
This is my controller's method that I call throught Ajax in the view:
public function getField(){
// Current User
$user_id = \Auth::user()->id;
$users = User::find($user_id)->users();
return Datatables::of($users )
->editColumn('id', 'Edit')
->editColumn('fields_id', function($users) {
$mystring = '';
$fields_id_array = json_decode($users->fields_id);
foreach($fields_id_array as $f_id){
/* this works */
// $mystring .= Fields::where('id', '=', $f_id) -> pluck('field_name');
/* this doesn't work */
$mystring .= Fields::find($f_id) -> pluck('field_name');
}
return $mystring;
})
->rawColumns(['id'])
->make(true);
}
The field 'fields_id' in users table is a JSON field like this: ['1','2','5'] and these refers to the id's of another table: 'Fields'.
I have already read this questions but I think my db table is it ok because increments are primary-key equivalent in Laravel migrations.
This is my migration for the table 'fields':
public function up()
{
Schema::defaultStringLength(191);
Schema::create('fields', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('code')->unique();
$table->string('param1');
$table->string('param3')->nullable();
$table->timestamps();
});
}
Thanks
a wild guess here, based on your last comment...
try this inside you loop
$mystring .= Fields::find(intval($f_id))->pluck('field_name');
I've added the intval() function arround your $f_id since you said you said they are in this format ['1','2','5']. that is an array of strings (that should be cast to integers if you plan to use them with find() function.
I am trying to do a simple group by 'alpha' in my loop for a glossary page but not sure how to achieve this. My data is
alpha glossary_title
A Apple B Banana A Another Apple!
GlossaryController.php
public function index() {
$glossary = Glossary::groupBy('alpha')->orderBy('glossary_title', 'asc')->get();
return View::make('glossary')->with('glossary', $glossary);
}
migration
Schema::create('glossary', function(Blueprint $table)
{
// columns
$table->increments('id');
$table->string('glossary_title');
$table->text('glossary_desc')->nullable();
$table->char('alpha', 1);
$table->timestamps();
});
glossary.blade.php
#foreach($glossary as $glossary)
<li>{{ $glossary->glossary_title}} <br /> {{ $glossary->glossary_desc}}</li>
#endforeach
This will return a new collection groupped by $glossary->alpha:
$glossary = Glossary::orderBy('glossary_title', 'asc')->get();
$glossary = $glossary->groupBy('alpha');
// same as this:
$glossary = $glossary->groupBy(function ($entry) {
return $entry->alpha;
});
You will need 2 loops in your view then, first for groups, second for entries in each group.