首页 > 解决方案 > 如何使用 laravel 5.8 在控制器中创建条件?

问题描述

你好朋友我有这个问题......我有表奖,users_profile ..在奖项中我保留图像,描述和分数所以在我的控制器中我想要做的是以下......如果用户有必要积分领取此奖品,然后他领取,如果他没有足够的积分,他将显示错误消息

public function reclamarpremios(Request $request)
{
    $vago_puntos = request('vago_puntos');
    $premioID = request('id');
    $puntaje = request('puntaje');
    $perfil_users_app_id = request('perfil_users_app_id');
    $us = UserAppPerfil::where('id',$perfil_users_app_id);
    $reclamo = Premios::where('id',$premioID)->where('puntos','=',$vago_puntos);
    if(!$reclamo->exists())
    {
        $us->decrement('vago_puntos',$puntaje);
        $reclamo->increment('veces_reclamado');
        return response()->json([$us,$reclamo,'message' => 'Felicidades has reclamado esta promocion, el equipo de vagos estara en contacto con tigo para obtorgarte tu premio'],200);

    }else{
        return response()->json(['message'=>'No tienes los suficientes vagos puntos'],422);  
    }

}

这段代码工作了一半,因为例如,如果一个用户有 1000 分,而奖品价值 500 分,那么他不会交换它(他把我送到其他地方)......如果我想要的是在某些领域添加并减去某些值,除了显示消息 this is my table in MySQL 数据库我在 DB 上的表

标签: phpmysqllaravelormeloquent

解决方案


我无法理解->where('puntos','=',$vago_puntos)这一行中的第二个条件():

$reclamo = Premios::where('id',$premioID)->where('puntos','=',$vago_puntos);

用户想要兑换的奖品是id等于的奖品$premioID,不是吗?如果是这样,你不需要那个条件。

public function reclamarpremios(Request $request)
{
    $vago_puntos = request('vago_puntos');

    $premioID = request('id');  //The prize id
    $puntaje = request('puntaje');
    $perfil_users_app_id = request('perfil_users_app_id');
    $us = UserAppPerfil::where('id',$perfil_users_app_id)->first();

    //Get the prize the user wants to redeem:
    $reclamo = Premios::where('id',$premioID)->first();
    if ($reclamo != null) { // if the prize exists
        $requiredPoints = $reclamo->puntos; //The required amount of points for that prize
        $userPoints = $us->puntos; //The user available points
        if ($userPoints >= $requiredPoints) {
            // if the user has the required amount of points, can redeem the prize:
            $us->decrement('vago_puntos',$puntaje);
            $reclamo->increment('veces_reclamado');
            return response()->json([$us,$reclamo,'message' => 'Felicidades has reclamado esta promocion, el equipo de vagos estara en contacto con tigo para obtorgarte tu premio'],200);
        }
        else {
            return response()->json(['message'=>'No tienes los suficientes vagos puntos'],422);
        }
    }else{
           return response()->json(['message' => 'This prize is not available']);
    }
}

希望能帮助到你。


推荐阅读