5. Sử dụng token ajax trong Lavarel (ok)

https://viblo.asia/p/tap-20-validation-laravel-GrLZDWAEKk0

C:\xampp\htdocs\blog\resources\views\create_post.blade.php

<h1>Create new post</h1>
<form action="/post" method="POST">
    @csrf
    <div>
        <p>Title</p>
        <input type="text" name="title">
    </div>
    <div>
        <p>Body</p>
        <textarea name="body" cols="30" rows="10"></textarea>
    </div>
    <br>
    <div>
        <button type="submit">Create</button>
    </div>
</form>
<script src="http://localhost/library/jquery/jquery.min.js"></script>
<script>
    $('form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: '/post',
            type: 'POST',
            data: {
                _token: $('input[name=_token]').val(),
                title: $('input[name=title]').val(),
                body: $('textarea[name=body]').val()
            }, success: function(res) {
                //
            }, error: function(error) {
                console.log(error);
            }
        })
    })
</script>

C:\xampp\htdocs\blog\app\Http\Controllers\PostController.php

public function create() {
    return view('create_post');
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request) {
    $validatedData = $request->validate([
      'title' => 'required|max:10',
      'body'  => 'required|min:5',
    ]);
  }

C:\xampp\htdocs\blog\routes\web.php

Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');

Last updated