如何在存储到数据库

时间:2018-04-27 10:44:24

标签: laravel laravel-5 laravel-5.5

我希望我的控制器检查数据库中的avis表,如果在将用户的注释存储在avis表中之前已存在user_id,以防止同一用户在某人的个人资料上提交多个推荐。有没有办法用laravel做到这一点?

我有一个avis表,用于存储id,profile_id,user_id,comment的推荐书。 (user_id获取提交表单的id和profile_id获取正在接收证明的用户的id)

这是我的控制器

public function store(AvisCreateRequest $request)
{
    //dd($request->all());
    //$region = $this->regionRepository->store($request->all());



    $avis = new Avis;

    $id = Auth::user()->id;

    /** $duplicates = Avis::search(function ($avis, $rowId) use ($request) {
        return $avis->user_id === $id;
    });

   if ($duplicates->isNotEmpty()) {
        return back()->with('success_message', 'You already submitted an avis');
    } **/

    $avis->comment = $request->comment;
    $avis->profile_id = $request->profile_id;

    $avis->user_id = $id;



    //dd($avis);

    $avis->save();

     return back()->with('success_message', 'Votre Avis a ete envoyez avec succes!');
}

这是我的表格

div id="avisForm">  

  <p class="feedback_message">We are here to make sure you are sastified and your transactions are safe. We do appreciate and will respond quickly to any feedback from you.</p>

    {!! Form::open(['route' => 'avis.store']) !!}

     <input type="hidden" name="profile_id" value="{{ $profiledetail->id }}">
     {!! Form::textarea('comment', null, ['placeholder' => 'Message', 'required' => 'required']) !!}
     {!! Form::submit('Envoyez', ['class' => 'formBtn','style' => 'margin-top:10px']) !!}

   {!! Form::close() !!}
</div>

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

$id = \Auth::user()->id;
$profile_id = $request->profile_id;

if (Avis::where('user_id', $id)->where('profile_id', $profile_id)->exists()) {
   return back()->with('success_message', 'You already submitted...');
}