将数据插入laravel后重定向并显示成功消息

时间:2018-09-23 17:28:29

标签: laravel

您好,盖伊兹,我想重定向回表单以输入新数据,该数据实际上是form.blade.php视图。我可以看到已成功插入数据,但如何通过成功消息进行重定向。我的代码已经给出。

public function store(Request $request)
{
   $sname = $request->input('sname');
   $fname = $request->input('fname');
   $gradyear = $request->input('gradyear');
   $phone = $request->input('phone');
   $email = $request->input('email');
   $paddress = $request->input('paddress');
   $prog = $request->input('prog');
   $job = $request->input('job');
   $org = $request->input('org');
   $position = $request->input('position');

   $data = array(
       'sname' => $sname,
       "fname" => $fname,
       "gradyear" => $gradyear,
       "phone" => $phone,
       "email" => $email,
       "paddress" => $paddress,
       "prog" => $prog,
       "job" => $job,          
       "org" => $org,
       "position" => $position
   );

   DB::table('tests')->insert($data);
   echo "Data inserted Successfully";
}

3 个答案:

答案 0 :(得分:0)

在控制器中:

public function store(Request $request)
{
    //
    return back()->with('success', 'Data inserted Successfully');
}

刀片中:

@if(session()->has('success'))
    <div class="alert alert-success">
        {{ session()->get('success') }}
    </div>
@endif

答案 1 :(得分:0)

假设以上代码按您想要的方式工作,则可以使用刷新的会话数据进行重定向:

public function store(Request $request)
{
   $sname = $request->input('sname');
   $fname = $request->input('fname');
   $gradyear = $request->input('gradyear');
   $phone = $request->input('phone');
   $email = $request->input('email');
   $paddress = $request->input('paddress');
   $prog = $request->input('prog');
   $job = $request->input('job');
   $org = $request->input('org');
   $position = $request->input('position');

   $data = array(
       'sname' => $sname,
       "fname" => $fname,
       "gradyear" => $gradyear,
       "phone" => $phone,
       "email" => $email,
       "paddress" => $paddress,
       "prog" => $prog,
       "job" => $job,          
       "org" => $org,
       "position" => $position);

   DB::table('tests')->insert($data);

   return back()->with('status', 'Data inserted Successfully!');

}

在刀片文件中,您可以使用以下内容进行渲染:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

  

https://laravel.com/docs/5.7/redirects#redirecting-with-flashed-session-data

答案 2 :(得分:0)

在代码后的控制器上

return back()->with('status', 'successfully inserted');

在表单视图上

 @if(session('status')
    {{ session('status') }}
    @endif

您可以在选择的CSS中格式化消息