Laravel Tutorial – CRUD (Create Read Update Delete) Operations in Laravel

by Admin


Posted on August 24, 2014 at 9:00 PM

Tags : : laravel


If you haven’t installed the Laravel application on your server, go through the Laravel installation and configuration tutorial first. Here we’ll provide the advanced functionality (fetch, add, edit, and delete) implementation guide in Laravel. For your better understanding, we’ll create an example blog post management application with Laravel 5.

 

In our previous Laravel 5 tutorial, we have learned how to install and configure Laravel application on Windows or Ubuntu. Now you’ll learn the most used functionality in this third part of the Laravel tutorial. In this tutorial, we’ll create a simple CRUD application with Laravel 5. Our step-by-step guide for beginners helps you to implement CRUD (Create, Read, Update, and Delete) Operations in Laravel.

If you haven’t installed the Laravel application on your server, go through the Laravel installation and configuration tutorial first. Here we’ll provide the advanced functionality (fetch, add, edit, and delete) implementation guide in Laravel. For your better understanding, we’ll create an example blog post management application with Laravel 5.

CRUD Operations in Laravel 5

To demonstrate view, add, edit, and delete functionality, we’ll show the post management system in Laravel 5. This sample Laravel CRUD application has the following functionality.

  • Retrieve posts data from the database and listed in the web page.
  • Fetch post details.
  • Add a new post and insert post information into the database.
  • Edit post and update post information into the database.
  • Delete post data from the database.

Database Table Creation

To store posts data a table need to be created in the database. Follow the below steps to create a posts table in the MySQL database.

  • Navigate to the root directory of Laravel application.
    cd /var/www/html/laravel
  • Create a new database migration for “posts” table.
    php artisan make:migration create_posts_table --create=posts
  • Open the database/migrations/xxxxxx_create_posts_table.php file and add the fields to store the basic information:
    increments('id');
                $table->string('title', 100);
                $table->text('content');
                $table->dateTime('created');
                $table->dateTime('modified');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('posts');
        }
    }
  • Use migrate Artisan command to run the migrations.
    php artisan migrate

Model Creation (Post)

Define a Post model that communicates with “posts” table.

php artisan make:model Post

The newly created Post model will be located in “app/” directory. Open the app/Post.php file and specify the fillable attribute for mass assignment and define the custom timestamps name.



Controller Creation (Posts)

Controllers are stored in the app/Http/Controllers directory and used to group request handling logic into a single class. To handle all the posts related request, define a PostsController by creating a app/Http/Controllers/PostsController.php file.
The PostsController has the following methods to handle CRUD operations.
index() – Retrieve posts data from the database via Post model and load the posts list view.
details() – Get the post details by ID and load the post details view.
add() – Load the post adding form view.
insert() – Validate submitted post data and insert into the database via Post model, and redirect the user to the posts list page.
edit() – Load the post editing form view.
update() – Validate submitted post data and update respective post data, and redirect the user to the posts list page.
delete() – Delete existing post data from the database via Post model and redirect the user to the posts list page.

get();
        
        //pass posts data to view and load list view
        return view('posts.index', ['posts' => $posts]);
    }
    
    public function details($id){
        //fetch post data
        $post = Post::find($id);
        
        //pass posts data to view and load list view
        return view('posts.details', ['post' => $post]);
    }
    
    public function add(){
        //load form view
        return view('posts.add');
    }
    
    public function insert(Request $request){
        //validate post data
        $this->validate($request, [
            'title' => 'required',
            'content' => 'required'
        ]);
        
        //get post data
        $postData = $request->all();
        
        //insert post data
        Post::create($postData);
        
        //store status message
        Session::flash('success_msg', 'Post added successfully!');

        return redirect()->route('posts.index');
    }
    
    public function edit($id){
        //get post data by id
        $post = Post::find($id);
        
        //load form view
        return view('posts.edit', ['post' => $post]);
    }
    
    public function update($id, Request $request){
        //validate post data
        $this->validate($request, [
            'title' => 'required',
            'content' => 'required'
        ]);
        
        //get post data
        $postData = $request->all();
        
        //update post data
        Post::find($id)->update($postData);
        
        //store status message
        Session::flash('success_msg', 'Post updated successfully!');

        return redirect()->route('posts.index');
    }
    
    public function delete($id){
        //update post data
        Post::find($id)->delete();
        
        //store status message
        Session::flash('success_msg', 'Post deleted successfully!');

        return redirect()->route('posts.index');
    }
    
}

Routing

To integrate the CRUD operations, we need to define 7 routes: a route to display posts list, a route to view post details, a route to display add form, a route to insert post data, a route to display edit form, a route to update post data, and a route to delete existing post data.
Open the app/Http/routes.php file and point URLs to the respective method of the Posts controller.

name('posts.index');
Route::get('/posts/details/{id}', 'PostsController@details')->name('posts.details');
Route::get('/posts/add', 'PostsController@add')->name('posts.add');
Route::post('/posts/insert', 'PostsController@insert')->name('posts.insert');
Route::get('/posts/edit/{id}', 'PostsController@edit')->name('posts.edit');
Route::post('/posts/update/{id}', 'PostsController@update')->name('posts.update');
Route::get('/posts/delete/{id}', 'PostsController@delete')->name('posts.delete');

Layouts

For this sample Laravel CRUD application, we’ll create a custom layout. Create resources/views/layouts/app.blade.php file and place the webpage HTML except the main content.


 

Laravel CRUD Operations - Basic

CRUD (Create Read Update Delete) Operations in Laravel

@yield('content')

Views

All the views related to the post management are placed in the resources/views/posts directory.

index.blade.php:
This view listed the posts data with details, add, edit, and delete links.

@extends('layouts.app')

@section('content')

        @if(Session::has('success_msg'))

{{ Session::get('success_msg') }}

        @endif     @if(!empty($posts))

Posts List

Add New

                    @foreach($posts as $post)                     @endforeach

Title Content Created Action

{{$post->title}}

{{$post->content}}

{{$post->created}}

Details Edit Delete

    @endif

@endsection

details.blade.php:
This view shows the details information about a particular post.

@extends('layouts.app')

@section('content')

Read Post

Back

Title:             {{ $post->title }}

Content:             {{ $post->content }}

Published On:             {{ $post->created }}

@endsection

add.blade.php:
This view renders a form that allows user to add post information.

@extends('layouts.app')

@section('content')

        @if($errors->any())            @foreach($errors->all() as $error)

{{ $error }}

            @endforeach()         @endif

Add a New Post Back

                    {{ csrf_field() }}

Title

Content

@endsection

edit.blade.php:
This view renders a form with post information and allows user to update post information.

@extends('layouts.app')

@section('content')

        @if($errors->any())            @foreach($errors->all() as $error)

{{ $error }}

            @endforeach()         @endif

Edit Post Back

                    {{ csrf_field() }}

Title

Content

{{ $post->content }}

@endsection

Test Application

Now it’s time to test the sample Laravel CRUD application. Run the Posts controller URL (http://example.com/posts) on the browser, you’ll see the posts list with add, edit and delete links.

laravel-tutorial-list-view-add-edit-delete-codexworld

 

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Download Source Code

Source: https://www.codexworld.com/laravel-tutorial-crud-add-edit-delete-operations/



Comments


You must be loged to add a comment !