Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

store and update using same function in laravel 8

Store and Update using same Function in Laravel

Today, I will give you an example of “How to Store and Update using same Function in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and Laravel 9 application.

First, what we’re doing here, This is the example :

use same form for create and edit laravel


Laravel use same form for create and edit

use of any route in laravel

Need of use the same form for create and edit in Laravel

Sometimes we need to use the same form to create and edit in our Laravel application but it is not a good practice.

Whenever we work on mini-projects on laravel for example simple e-commerce, in that case, we add the multiple delivery address on the checkout page, so we use only a single form to create and edit user addreess.

Let’s get started.

Generating Migration with Model

php artisan make:model Book -m

Migration Structures

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('book_name');
            $table->string('book_author');
            $table->string('book_description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

Run Migration

php artisan migrate

app\Models\Book.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
}

Create a Controller

php artisan make:controller BookController

Define Web Routes

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;

/*
|--------------------------------------------------------------------------
| 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::get('/book-list', [BookController::class, 'bookList'])->name('book.list');
Route::any('/add-edit-book/{id?}', [BookController::class, 'addeditBook'])->name('addedit.book');

Recommended article:- Use of Any Route in Laravel.

app\Http\Controllers\BookController.php

<?php

namespace App\Http\Controllers;
use Session;
use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{

    public function bookList(){
        $books = Book::get();
        return view('example.list',compact('books'));
    }

    public function addeditBook(Request $request, $id=null){

         if($id== ""){
            $book  = new Book;
           
        }else{
            $book = Book::find($id);
        }
        if($request->isMethod('post')){
            $data = $request->all();
            $book->book_name  = $data['name'];
            $book->book_author  = $data['author'];
            $book->book_description = $data['description'];
            $book->save();
            return redirect()->route('book.list') ;
         }else{
        return view('example.add_edit_book',compact('book'));
        }
    }
}

Create Blade Files

We create an example folder in views and then make these 2 files given below-:

  • list.blade.php
  • add_edit_book.blade.php

resources\views\example\list.blade.php

list blade file
<!doctype html>
<html lang="en">
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
       <div class="container">
       <h3>Laravel 8 use same form for create and edit Example</h3>
       <a href="{{route('addedit.book')}}"><button type="button" class="btn btn-success btn-sm btn pull-right">Add new Book</button></a>
       <table class="table table-bordered">
         <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Author</th>
            <th>Action</th>
         </tr>
         @if(isset($books) && !empty($books))
         @foreach ($books as $key => $book )
         <tr>
            <td>{{ $key+1 }}</td>
            <td>{{ $book->book_name }}</td>
            <td>{{ $book->book_author}}</td>
            <td>
               <a href="{{route('addedit.book',$book['id'])}}" class="btn btn-primary" role="button">Edit</a>
            </td>
         </tr>
         @endforeach
         @endif
      </table>
   </div>
   </body>
</html>

resources\views\example\add_edit_book.blade.php

create blade file
<!DOCTYPE html>
<html>
   <head>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
      <style>
         a {
         color: #BE206B!important;
         }
         a.btn.btn-lg.btn-block,.btn-info {
         color: white !important;
         }
         .btn-secondary {
         background-color: #448BC6!important;
         color: #fff!important;
         }
         button.btn.btn.btn-secondary {
         width: 100%;
         }
         h3 {
         text-align: center;
         line-height: 200%;
         }
         .collpa
         .pt-0, .py-0 {
         padding-top: 0!important;
         }
      </style>
   </head>
   <main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Store and Update using the same Function in Laravel.</a></h3>
                   <form role="form" @if(empty($book['id'])) action="{{route('addedit.book')}}" @else action="{{route('addedit.book',$book['id'])}}" @endif method="POST">
                     @csrf
                     <div class="form-group">
                        <label for="name">Book name <span class="text-danger">*</span></label>
                        <input type="text" name="name" value="{{$book['book_name']}}" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="author">Book Author<span class="text-danger">*</span></label>
                        <input type="text" name="author" value="{{$book['book_author']}}" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="description">Book Description <span class="text-danger">*</span></label>
                        <textarea name="description" class="form-control" rows="4" cols="50">{{$book['book_description']}}</textarea required>
                     </div>
                     <div class="form-group">
                     <button type="submit" class="btn btn btn-secondary">save</button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
   </body>
</html>

Run Application :

127.0.0.1:8000/book-list
laravel update or create using same function
127.0.0.1:8000/add-edit-book
Laravel 8 use same form for create and edit

use the same form for create and edit in laravel
127.0.0.1:8000/add-edit-book/2
add and update using single function in laravel

In this article, we successfully learned “How to store and update using same function in laravel 8”, I hope this article will help you with your Laravel application Project.

Read also :- Controller Route Groups in Laravel 9.