Laravel CRUD Example; In this tutorial you will learn step by step guide on how to create a CRUD operation in laravel from scratch. Laravel is the most valuble and famous php framework. CRUD operations are basic data manipulation for database.
This post contains laravel crud application which will perform all these operations on a MySQL database table at one place. Let’s start Laravel CRUD example tutorial step by step from scratch for beginners.
Laravel CRUD Example
Use to ollow the following steps to implement a basic crud operation in laravel application.
- Step 1: Download Laravel App
- Step 2: Connect Database to App
- Step 3: Create Model & Migration
- Step 4: Add Routes
- Step 5: Create Resource Controller
- Step 6: Create Blade Files
- Step 7: Run Laravel Application
Download Laravel App
First create new laravel project adding the following command in terminal.
composer create-project --prefer-dist laravel/laravel laravel-crud
Go inside the app
cd laravel-crud
Connect Database to App
Now, you need to create the mysql database and connect that database to the Laravel application. Open you localhost/phpmyadmin and add a new database name then add the credentials in .env file which is showing in your project root.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelblog #your_database_name
DB_USERNAME=root #your_database_username
DB_PASSWORD=admin #your_database_password
Now you can add you tables easily with mysql database.
Create Model and Migration
Now generate model and migration file just adding the below command in your terminal which is generate a model file and migration which will show your database table after running the migration command.
php artisan make:model Post -m
Add Fillable Property: In your app/models inside generated a new file Post.php file where you need to add fillable properties. So, open the app/models/Post.php file add the following code on it;
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'title', 'description'
];
}
Next, you can see in your database migration directory created a new file same as below, here you need to add you database columns. So open the database\migrations\2020_09_27_115954_create_posts_table.php file and add the columns on it;
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration {
/**
* Run the migrations.
*
* @return void */
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title')->nullable();
$table->longText('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
After adding the columns now run the below command which is generate table in your database.
php artisan migrate
Step 5: Create routes
In laravel route section have some change here you need to use your controller then initialize the controller class. Open your “routes/web.php” file and your routes same as below.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('posts', PostController::class);
Route::get('/', function () {
return view('welcome');
});
Create controller
Now you need to create a controller just adding the below command and generate a new resource controller PostController.
php artisan make:controller PostController --resource
After running this command you will find new file in this path “app/Http/Controllers/PostController.php”. Where you saw here already created methods same like below. Now you need put below codes on your functions.
- index()
- create()
- store()
- show()
- edit()
- update()
- destroy()
Next open the app/Http/Controllers/PostController.php file and add the below code on it;
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')->with('success','Post created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('posts.show',compact('post'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.edit',compact('post'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$post->update($request->all());
return redirect()->route('posts.index')->with('success','Post updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success','post deleted successfully');
}
}
Create Blade Files
Here in this step we create our view files. First create two folder one is “layouts” and another is “posts”. In layout folder create app.blade.php file and and inside posts folder create another blade files.
If you don’t know to integrate our blade files in laravel then please check first here how to integration laravel bootstrap admin panel. Now create below blade files for your crud app:
- resources/views/layouts/app.blade.php
- resources/views/posts/index.blade.php
- resources/views/posts/create.blade.php
- resources/views/posts/edit.blade.php
- resources/views/posts/show.blade.php
So let’s just create following files and put bellow code.
resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Laravel 5.8 CRUD Example Tutorial</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
resources/views/posts/index.blade.php
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Laravel 9 CRUD Example from scratch </h2> </div> <div class="pull-right"> <a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Product</a> </div> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> <p>{{ $message }}</p> </div> @endif <table class="table table-bordered"> <tr> <th>Title</th> <th>Body</th> </tr> @foreach ($posts as $post) <tr> <td>{{ $post->title }}</td> <td>{{ $post->body }}</td> <td> <a class="btn btn-info" href="{{ route('posts.show',$post->id) }}">Show</a> <a class="btn btn-primary" href="{{ route('posts.edit',$post->id) }}">Edit</a> <form action="{{ route('posts.destroy',$post->id) }}" method="POST"> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </table> @endsection
resources/views/posts/create.blade.php
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Add New Post</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a> </div> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('posts.store') }}" method="POST"> @csrf <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> <input type="text" name="title" class="form-control" placeholder="Title"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Body:</strong> <textarea class="form-control" style="height:150px" name="body" placeholder="Post Body"></textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
resources/views/posts/edit.blade.php
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Edit Post</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a> </div> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('posts.update',$post->id) }}" method="POST"> @csrf @method('PUT') <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Title:</strong> <input type="text" name="title" value="{{ $post->title }}" class="form-control" placeholder="Title"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Body:</strong> <textarea class="form-control" style="height:150px" name="body" placeholder="Post Body">{{ $post->body }}</textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
resources/views/posts/show.blade.php
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2> Show Post</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a> </div> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> {{ $post->title }} </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Body:</strong> {{ $post->body }} </div> </div> </div> @endsection
Run Your Application
Lets run this crud application example with laravel 9 so run bellow command
php artisan serve
Now you can open bellow URL on your browser
http://localhost:8000/posts
So friends its very easy way to Laravel CRUD operation step by step. Hope this tutorial help you to learning laravel 9 crud tutorial. If you have any question regarding laravel crud operation generator then please comment below we appreciate your comment.
1 thought on “Laravel CRUD Operation Tutorial with Example from Scratch”