当我要保存与用户有关的新东西时,在表中插入Userid:Laravel

时间:2019-02-13 09:41:25

标签: php laravel laravel-5 laravel-5.6

在我的项目中,我有很多与用户有关的东西,当我要保存其中的某物时,我一直都想与之保存。 示例:此用户有一个保存的信用卡,可以将此数据与该用户相关联,我在信用卡的用户ID列中添加了该数据,因此我尝试添加用户ID时出现错误

这是我的控制器:

<?php

namespace App\Http\Controllers;

use App\CreditCards;
use Illuminate\Http\Request;
use App\ads;
use Validator, Hash;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Config;
use Artisan;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Password;
use Carbon\Carbon;

class CreditsCardsController extends Controller
{
    public function index(Request $request)
    {
        # code...
      //  $Ads = ads::all();
        //  return $this->sendResponse($Ads->toArray(), 'Ads read succesfully');
        // This is the name of the column you wish to search
        $input = $request->all();
        $validator =    Validator::make($input, [
            'user_id'=> 'required'
        ] );

          $Cards = CreditCards::where('user_id','=', $request->user_id)->first();

        return response()->json(['Cards'=>$Cards]);
    }

    public function stockcards (Request $request){
        $input = $request->all();
        $validator =    Validator::make($input, [
            'number_card'=> 'required',
            'expired_date'=> 'required',
            'ccv'=> 'required'
        ] );

        if ($validator -> fails()) {
            # code...
            return response()->json($validator->errors());

        }

        $Cards = CreditCards::create($input);
        //return $this->sendResponse($ads->toArray(), 'Ads created succesfully');
        return response()->json(['Cards'=>$Cards]);
    }
}

这是我的模态,在这里我得到一个错误:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;
class CreditCards extends Model
{
    protected $fillable = [
        'number_card', 'expired_date', 'ccv','user_id = '. Auth::user()->id .',
    ];
}

这是我的迁移表:

   Schema::create('ads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('path');
            $table->timestamps();
        });

1 个答案:

答案 0 :(得分:0)

您没有在$fillable属性中设置默认值。也许您可以在用例中使用mutators,如下所示:

class SomeModel extends Model
{
    public function setUserIdAttribute($value)
    {
        $this->attributes['user_id'] = Auth::id();
    }
}