checkbox controller in laravel - laravel

Hello this is my controller in laravel and I am not getting the problem here. It checks the file if I manually enter a dataset with the value of 1 but if I do it with the system it does not update the value and the box remains to 0 with unchecked box.
What I am trying to do is tick the box if the user tick it and keep the box ticked until he ticks it off plus update the database value too. Thank you in advance
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id);
// if($this->request->isMethod('get')) {
// if($user->can('untick', $uploads)) {
// $uploads = $this->upload = 0;
// } else {
// return $uploads = $this->upload = 1;
// }
// }
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads = $this->upload = 1;
} else if($type == 1){
$uploads = $this->upload = 0;
}
}
if(isset($_POST["uploaded"]) && !empty($_POST["uploaded"])) {
$uploads->uploaded = $this->request->uploaded;
$uploads->save();
}
return redirect('/home');
}

I have sorted this out. I was not getting the requesting value from the form as you can see here $uploads->uploaded = $this->upload = 1; so here is the updated code which I did and worked.
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id); //gets upload id
// requesting uploaded value either 0 or 1
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads->uploaded = $this->request->upload = 1;
} else if($type == 1) {
$uploads->uploaded = $this->request->upload = 0;
}
}
$uploads->save(); // saving the value in database
return redirect('/home');
}
Thank you d3r1ck for the help though ... :)

Related

Sorting League Standings table

Am doing a league management system where the system generates fixtures and assign each match to an official who later enters results. Now when i have set everything possible for the log table but when i pass the results, am getting the some few errors : Too few arguments to function App\Models\Gamescores::updateStandings(), 0 passed in E:\Video\laraVids\laraProjects\HAM\app\Models\Gamescores.php on line 28 and exactly 1 expected
here is my code for the sorting of the league
class Gamescores extends Model
{
use HasFactory;
protected $table = 'gamescores';
protected $fillable = [
'games_id',
'away_score',
'home_score',
];
public function game()
{
return $this->belongsTo(Game::class, 'games_id');
}
public static function boot()
{
parent::boot();
static::created(function ($gamescore) {
$gamescore->updateStandings();
});
}
public function updateStandings($league_id)
{
// Get all gamescores for the specified league
$gameScores = Gamescores::whereHas('game', function ($query) use ($league_id) {
$query->where('league_id', $league_id);
})->get();
// Loop through each gamescore and update the log table for each team
foreach ($gameScores as $gameScore) {
$game = Games::find($gameScore->games_id);
$league_id = $game->league_id;
$home_team_id = $game->home_team;
$away_team_id = $game->away_team;
$home_team_log = Logtable::where('team_id', $home_team_id)->first();
if ($home_team_log !== null) {
$home_team_log->played += 1;
if ($gameScore->home_score > $gameScore->away_score) {
$home_team_log->won += 1;
$home_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$home_team_log->drawn += 1;
$home_team_log->points += 1;
} else {
$home_team_log->lost += 1;
}
$home_team_log->goals_for += $gameScore->home_score;
$home_team_log->goals_against += $gameScore->away_score;
$home_team_log->goal_difference = $home_team_log->goals_for - $home_team_log->goals_against;
$home_team_log->save();
}
$away_team_log = Logtable::where('team_id', $away_team_id)->first();
if ($away_team_log !== null) {
$away_team_log->played += 1;
if ($gameScore->away_score > $gameScore->home_score) {
$away_team_log->won += 1;
$away_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$away_team_log->drawn += 1;
$away_team_log->points += 1;
} else {
$away_team_log->lost += 1;
}
$away_team_log->goals_for += $gameScore->away_score;
$away_team_log->goals_against += $gameScore->home_score;
$away_team_log->goal_difference = $away_team_log->goals_for - $away_team_log->goals_against;
$away_team_log->save();
}
}
}
}
thats my model where am passing the method to genererate the results
public function fixtureToView($league)
{
// Fetch all rows from the games table, including the related official model
$games = Games::where('league_id', $league)->get();
// Extract the values for the role column as an array
$pluckedFixtures = $games->pluck('Fixture')->toArray();
// Count the number of occurrences of each value in the array
$counts = array_count_values($pluckedFixtures);
// Initialize an empty array to store the duplicate keys and values
$fixtures = collect([]);
// Iterate over the counts array
foreach ($counts as $key => $count) {
// If the count is greater than 1, add the key and value to the duplicates array
$fixtures->push($games->where('Fixture', $key));
}
// In your controller
$gamescores = Gamescores::all();
foreach ($gamescores as $gamescore) {
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
if($gamescore->games_id){
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
}
}
$standings = Logtable::all();
$standings = $standings->sortByDesc('points');
// return view('standings', compact('standings'));
return view(
'admin.league.fixtures.index',
compact('fixtures', 'standings')
);
thats my controller where am passing the method to retrieve it in the view, what i want is the log table to get the Id of the league where the games/matches belong to
the error am getting this error

how to check count of likes and dislike for post for rating sysytem

i am making an system to check count of likes and dislike if like count is more then dislike count then it gives true
but i am getting an error
// if (Files::withCount('likes') >= Files::withCount('dislike')) {
// return response()->json(['true']);
// }elseif (Files::withCount('dislike') >= Files::withCount('like')) {
// return response()->json(['false']);
// }else{
// return response()->json(['error'=>'somethingwenrwrng']);
// }
// if( DB::table('files')->select('files_id')
// ->join('likes','files_id.files_id','=','files_id') > DB::table('files')->select('id')
// ->join('dislike','files_id.files_id','=','files_id') ){
// return response()->json(['true']);
// }else {
// return response()->json(['error'=>'somethingwenrwrng']);
// }
$file = Files::find($id);
if($file ->likes->count() > $file ->dislike->count() ){
return response()->json(['true']);
}else{
return response()->json(['error'=>'somethingwenrwrng']);
}
i have tried different method to check but getting an error
the withCount() method return a property of the related field_count counting related models
so
$file = Files::find($id)->withCount(['likes','dislikes']);
if($file->likes_count > $file->dislikes_count ){
return response()->json(['true']);
}

Strange error session get destroyed

I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Pass fees from one shipping method to another

I have a tricky shipping issue that I'm trying to work out. I have a custom extension that calculates the table rates for all of the domestic shipping. But for international, one type of product(category A) is a flat $35/product shipping fee and the rest of the products (categories B and C) are calculated by UPS and USPS. The only way I've been able to figure out how to properly calculate shipping if a customer purchases both types of products is to create a table rate for Category A, then pass it along to UPS/USPS as a handling fee. Is there a variable/method I can use for this process? I haven't yet found one.
As requested, here's my function:
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
// Cut out code where it adds up the categories and the number of items in each category
$rates = $this->getRates($request, $_categories);
if (!empty($rates))
{
$rateTypes = array();
foreach($rates as $rate)
{
$rateTypes[] = $rate['method_name'];
}
$rateTypes = array_unique($rateTypes);
$i=0;
// Create array to pass along to UPS/USPS, if needed
$tempCategories = $_categories;
foreach($rateTypes as $rateType)
{
$groupPrice = 0;
foreach($_categories as $category=>$catQty)
{
$rateExists = false;
$standardRate = 0;
foreach($rates as $rate)
{
$rateCats = explode(',',$rate['category_list']);
if(in_array($category,$rateCats) && $rate['method_name'] == $rateType )
{
$rateExists = true;
if($rate['condition_type'] == 'I'){
$ratePrice = $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$ratePrice = $rate['price'];
}
unset($tempCategories[$category]);
}
else if(in_array($category,$rateCats) && $rate['method_name'] == "Standard" && $rateType != "Standard")
{
if($rate['condition_type'] == 'I'){
$standardRate += $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$standardRate += $rate['price'];
}
unset($tempCategories[$category]);
}
}
if($rateExists == false)
{
$groupPrice += $standardRate;
}
else
$groupPrice += $ratePrice;
}
if(count($tempCategories) > 0)
{
// Figure out how to pass the $groupPrice to other shipping methods here
}
else {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('shippingcodes');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('shippingcodes_'.$rateType);
$method->setMethodTitle($rateType);
$method->setPrice($groupPrice);
$result->append($method);
}
}
}
else
return false;
return $result;
}

Resources