Laravel
241
w3alert.com
10-01-2020
Laravel CRUD(Create, Read, Update, Delete) Example Tutorial. In this tutorial, you will learn how to insert, update, read, delete data from MySQL database table. And create CRUD (Create, Read, Update, Delete) application in Laravel.
This tutorial has the purpose to explain to you, how you easily insert, update, read, delete data from MySQL database tables and built a CRUD web application in Laravel.
First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:
composer create-project laravel/laravel Laravel-Crud-App –-prefer-dist
If you want to install a specific version of laravel, you can follow the following tutorial
https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer
After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_application_configuration DB_USERNAME=root DB_PASSWORD=root
Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.
Go to the command prompt
cd/project_root_directory
php artisan make:model Post -m
after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.
Your migration file looks like:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
And go to the app/ directory and find the model file.
Your model file looks like:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // }
Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :
.. use Illuminate\Support\Facades\Schema; .... function boot() { Schema::defaultStringLength(191); } ...
Next, go to command prompt and run the following command:
php artisan migrate OR php artisan migrate:fresh
This php artisan migrate command creates a table in your database.
Next step, go to routes/web.php file and update the following routes into your file:
//retrive data and display list Route::get('list','[email protected]'); //show insert form and store data into database Route::get('show-form','[email protected]'); Route::post('insert-record','[email protected]'); //display and update data into database Route::get('edit/{id?}','[email protected]'); Route::post('update-record','[email protected]'); //delete data into database laravel Route::get('delete/{id?}','[email protected]');
Now, you need to generate or create a controller file using artisan command, so use the php artisan make:controller command and create a new controller file:
php artisan make:controller PostController
In this controller file, we will create 5 methods for performing crud operation in laravel web application.
After that, go to App/Http/Controllers/ directory and find the created PostController file and update the following code into your file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response; use App\Post; class PostController extends Controller { public function index() { $data['posts'] = Post::paginate(10); return view('list', $data); } public function showForm() { return view('insert-form'); } public function insertRecord(Request $request) { $data = request()->validate([ 'title' => 'required', 'description' => 'required', ]); $check = Post::insert($data); return Redirect::to("show-form")->withSuccess('Great! Form successfully submit with validation.'); } public function edit(Request $request, $id) { $data['post'] = Post::where('id', $id)->first(); if(!$data['post']){ return redirect('/list'); } return view('edit', $data); } public function updateRecord(Request $request) { $data = request()->validate([ 'title' => 'required', 'description' => 'required', ]); if(!$request->id){ return redirect('/list'); } $check = Post::where('id', $request->id)->update($data); return Redirect::to("list")->withSuccess('Great! Form data successfully updated'); } public function deleteRecord(Request $request, $id) { if(!$id){ return redirect('/list'); } $check = Post::where('id', $id)->delete(); return Redirect::to("list")->withSuccess('Great! data successfully deleted'); } }
Next, you need to create some blade view files, so go resource/views directory and create the following blade views file.
Go to resource/views/insert-form.blade.php and update the following code:
<html> <head> <title>Laravel Insert Form Data Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> <form action="{{ url('insert-record') }}" method="post" accept-charset="utf-8">@csrf <div class="form-group"> <label class="control-label col-sm-2" for="fname">Title</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Title" name="title"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="comment">Description</label> <div class="col-sm-10"> <textarea class="form-control" rows="5" name="description"></textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </body> </html>
Next, Go to resource/views/edit.blade.php and update the following code:
<html> <head> <title>Laravel Update Form Data Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> <form action="{{ url('update-record') }}" method="post" accept-charset="utf-8">@csrf <input type="hidden" class="form-control" name="id" value="{{ $post->id }}"> <div class="form-group"> <label class="control-label col-sm-2" for="fname">Title</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Title" name="title" value="{{ $post->title }}"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="comment">Description</label> <div class="col-sm-10"> <textarea class="form-control" rows="5" name="description">{{ $post->description }}</textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </body> </html>
Next, Go to resource/views/list.blade.php and update the following code:
<html> <head> <title>Laravel Retrieve Data from Database</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <div class="row"> <a href="{{ url('insert-form') }}" class="btn btn-success mb-2">Add</a> <br> <div class="col-md-12"> <table class="table table-bordered" id="laravel_crud"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Description</th> <th>Created at</th> <td colspan="2">Action</td> </tr> </thead> <tbody> @foreach($posts as $post) <tr> <td>{{ $post->id }}</td> <td>{{ $post->title }}</td> <td>{{ $post->description }}</td> <td>{{ date('Y-m-d', strtotime($post->created_at)) }}</td> <td><a href="{{ url('edit/'.$post->id) }}" class="btn btn-primary">Edit</a></td> <td> <form action="{{ url('delete/'.$post->id) }}" method="get"> {{ csrf_field() }} <button class="btn btn-danger" type="submit">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> {!! $posts->links() !!} </div> </div> </div> </body> </html>
You can use the following command artisan command to start the development server:
php artisan serve
The final step, go to your browser and type the below-given URL into your browser:
http://localhost:8000/list OR http://localhost/Laravel-Crud-App/public/list
You can download the full source code of Laravel CRUD Application Here,
This tutorial idea has taken from the following urls: