Form
- stored in the resources/views directory
- forms accept user input and store in the database
Create a form
- In the resources/views/posts directory, create a new php file called create.blade.php
- The @csrf directive is used to generate hidden token input field that Laravel can use to prevent CSRF attack
@extends('layouts.app')
@section('title','Create a post')
@section('content')
<form action="{{route('posts.store')}}" method="POST"> //because we use Resource controller, we can call resourcename.action here to process the form request
@csrf //prevents CSRF attack
<div><input type="text" name="title"></div>
<div><textarea name="content" col="30" rows="10"></textarea></div>
<input type="submit" value="Submit">
</form>
@endsection
- In the routes directory, open web.php file and edit the following:
use App\Http\Controllers\PostController;
Route::post('/store', [PostController:class,"store"]);
- we have created the view and route, now we need to tell the controller to redirect to this view when the user wants to create a new record
- In the app/Http/Controller directory, open PostController.php file and edit the following:
use App\Models\BlogPost;
public function create(){
return view('posts.create');
}
public function store(Request $request){
$post = new BlogPost(); //create a new model instance
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save(); //save the data to the database
return redirect()->route('posts.show',['post',$post]); //redirect to the all posts page
}