Showing posts with label laravel crud. Show all posts
Showing posts with label laravel crud. Show all posts

Saturday, 16 July 2022

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5


In this tutorial, we are going to show you how to make CRUD Application Laravel 9 framework. We will explained you step by step, how can we perform CRUD Operation in Laravel 9 Framework. So if you beginner in Laravel framework then this tutorial will help you to build CRUD Application in Laravel 9 framework, and you will be able to create Laravel 9 CRUN Application. Here under this tutorial, we will use basic example to show you CRUD Operation in Laravel 9.

Recently Laravel has release Laravel 9 framework and in Laravel 9 framework there is several new features and LTS Support. Laravel 9 also introduced an Anonymous Sub Migration also and it also resolved migration class name Collison. One more things Laravel 9 framework has been use PHP 8 version and it has been support PHP string function, which are very useful for string operations. There are many new query builder function has been introduced under Laravel 9 framework which will more convenient when you have work with database operation. So you are learn Laravel framework first time then this tutorial will help you to create CRUD (Create, Read, Update and Delete) Operation in Laravel 9 framework.

In this tutorial, we will create Student CRUD Application in Laravel 9 framework. Under this CRUD Application we will make Application, in which we can Add new Student Data, with student image upload, edit or change existing student data, with form data validation, show single student data on the web page, delete or remove student data from data and fetch all student data from MySQL database and display on the web page in HTML table format with dynamic pagination link. We will also create table in MySQL database from this Laravel 9 application using Laravel 9 Migration, and after this, we will create Controller, Models and views file for student crud application. Under this Laravel 9 crud application we will use Bootstrap 5 library for design web page. You have to following below steps to create CRUD Application in Laravel 9 framework.


Step 1 - Download & Install 9


In the First Steps of Laravel 9 CRUD Application, we have to download and install fresh Laravel 9 Application in our computer. So for this, you have to goes to command prompt and then after goes into directory where you have run PHP 8 script and then after you have to run following command.


composer create-project --prefer-dist laravel/laravel laravel_9_crud


Once we have run this command then it will create laravel_9_crud directory and under this directory it will download and install Laravel 9 Application.

Step 2 - Make Database Connection


After install Laravel 9 application, first we need to create database connection with MySQL database. So for this we have to open .env file and under this file, we need to add MySQL database configuration like MySQL database name, MySQL database user namd and password details. Once we have define this details, then it will make MySQL database connection in Laravel 9 framework. Below you can find MySQL database configuration details.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 - Create MySQL Table using Laravel 9 Migration


Under this step, we have to crate students table under MySQL database from this Laravel 9 Application using Migrations. So first we have to create migration file under Laravel 9 application, so we have to run following command in command prompt.


php artisan make:migration create_students_table --create=students


After run above command then you will find one new file under database/migrations directory. So for we have to open that file and under that file, we have to define following code under that migrations file for create students table in MySQL database.


<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('student_name');
            $table->string('student_email');
            $table->enum('student_gender', ['Male', 'Female']);
            $table->string('student_image');
            $table->timestamps();
        });
    }

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



After above code in migration file, now for create table in MySQL database from this Laravel 9 application, so for this, we have to run following command in command prompt and it will migrate MySQL table defination to MySQL database and create students table in MySQL database from this Laravel 9 Application.


php artisan migrate





Step 4 - Create CRUD Model and Controller


Under this step, we have to create Controller and Models file for CRUD Operation. So for this, we have goes to command prompt and run following command, which will create new CRUD StudentController and Student Model class file under Laravel 9 framework.


php artisan make:controller StudentController --resource --model=Student


So after run above command it will create Student.php model class file under app/Models directory and we have to open that file and put following code under that file.

app/Models/Student.php

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;

    protected $fillable = ['student_name', 'student_email', 'student_gender', 'student_image'];
}



And after run above command it will also create CRUD Controller with name StudentController.php file under app/Http/Controllers directory.

So this StudentController.php file has been created with seven method by default which you can seen below.

  1. index() - This is root method of this Controller class.
  2. create() - This is method has been used for load Add student form in the browser.
  3. store() - This method has been used for handle Add student data request.
  4. show() - This method has been used for display single student data on the web page.
  5. edit() - This method has been used for load edit student form in the browser.
  6. update() - This method has been receive student update form data request.
  7. destroy() - This method has been used for delete student data from database.

For create CRUD Application, you have to put folliowing code under StudentController.php file.

app/Http/Controllers/StudentController.php app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Student::latest()->paginate(5);

        return view('index', compact('data'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'student_name'          =>  'required',
            'student_email'         =>  'required|email|unique:students',
            'student_image'         =>  'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $file_name = time() . '.' . request()->student_image->getClientOriginalExtension();

        request()->student_image->move(public_path('images'), $file_name);

        $student = new Student;

        $student->student_name = $request->student_name;
        $student->student_email = $request->student_email;
        $student->student_gender = $request->student_gender;
        $student->student_image = $file_name;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        return view('show', compact('student'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit(Student $student)
    {
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Student $student)
    {
        $request->validate([
            'student_name'      =>  'required',
            'student_email'     =>  'required|email',
            'student_image'     =>  'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $student_image = $request->hidden_student_image;

        if($request->student_image != '')
        {
            $student_image = time() . '.' . request()->student_image->getClientOriginalExtension();

            request()->student_image->move(public_path('images'), $student_image);
        }

        $student = Student::find($request->hidden_id);

        $student->student_name = $request->student_name;

        $student->student_email = $request->student_email;

        $student->student_gender = $request->student_gender;

        $student->student_image = $student_image;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Data has been updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy(Student $student)
    {
        $student->delete();

        return redirect()->route('students.index')->with('success', 'Student Data deleted successfully');
    }
}



Step 5 - Add Service Provider for Bootstrap Pagination


In Laravel 9 framework produce default style pagination link which will not properly display if you have Bootstrap library. So for this, we have to open app/Providers/AppServiceProvider.php and under this file, we have to add Paginator::useBootstrap() code under boot() method for support the bootstrap pagination.

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}



So after adding this code, you Laravel 9 application will display proper pagination link on the web page.

Step 6 - Create Views Blades File


Under this steps, we have to create blades files for display HTML output in the browser. In the Laravel 9 framework, blades files has been stored under resources/views directory. Under this Laravel 9 CRUD Application, we have to create following views blades files.

  1. master.blade.php - This is master template file.
  2. index.blade.php - This file we will used for display MySQL table data on the web page in HTML table format with pagination link.
  3. create.blade.php - This file has been used for load Create Student form on the web page.
  4. show.blade.php - This file has been used for display single student data on the web page.
  5. edit.blade.php - This file has been used for load student edit form in the browser.

Below you can find source code of all blade file.

resources/views/master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 CRUD Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        
        <h1 class="text-primary mt-3 mb-4 text-center"><b>Laravel 9 Crud Application</b></h1>
        
        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/index.blade.php

@extends('master')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-success">
	{{ $message }}
</div>

@endif

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Data</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.create') }}" class="btn btn-success btn-sm float-end">Add</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<table class="table table-bordered">
			<tr>
				<th>Image</th>
				<th>Name</th>
				<th>Email</th>
				<th>Gender</th>
				<th>Action</th>
			</tr>
			@if(count($data) > 0)

				@foreach($data as $row)

					<tr>
						<td><img src="{{ asset('images/' . $row->student_image) }}" width="75" /></td>
						<td>{{ $row->student_name }}</td>
						<td>{{ $row->student_email }}</td>
						<td>{{ $row->student_gender }}</td>
						<td>
							<form method="post" action="{{ route('students.destroy', $row->id) }}">
								@csrf
								@method('DELETE')
								<a href="{{ route('students.show', $row->id) }}" class="btn btn-primary btn-sm">View</a>
								<a href="{{ route('students.edit', $row->id) }}" class="btn btn-warning btn-sm">Edit</a>
								<input type="submit" class="btn btn-danger btn-sm" value="Delete" />
							</form>
							
						</td>
					</tr>

				@endforeach

			@else
				<tr>
					<td colspan="5" class="text-center">No Data Found</td>
				</tr>
			@endif
		</table>
		{!! $data->links() !!}
	</div>
</div>

@endsection


resources/views/create.blade.php

@extends('master')

@section('content')

@if($errors->any())

<div class="alert alert-danger">
	<ul>
	@foreach($errors->all() as $error)

		<li>{{ $error }}</li>

	@endforeach
	</ul>
</div>

@endif

<div class="card">
	<div class="card-header">Add Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.store') }}" enctype="multipart/form-data">
			@csrf
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
				</div>
			</div>
			<div class="text-center">
				<input type="submit" class="btn btn-primary" value="Add" />
			</div>	
		</form>
	</div>
</div>

@endsection('content')


resources/views/show.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Details</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.index') }}" class="btn btn-primary btn-sm float-end">View All</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Name</b></label>
			<div class="col-sm-10">
				{{ $student->student_name }}
			</div>
		</div>
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Email</b></label>
			<div class="col-sm-10">
				{{ $student->student_email }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Gender</b></label>
			<div class="col-sm-10">
				{{ $student->student_gender }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Image</b></label>
			<div class="col-sm-10">
				<img src="{{ asset('images/' .  $student->student_image) }}" width="200" class="img-thumbnail" />
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/edit.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">Edit Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.update', $student->id) }}" enctype="multipart/form-data">
			@csrf
			@method('PUT')
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" value="{{ $student->student_name }}" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" value="{{ $student->student_email }}" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
					<br />
					<img src="{{ asset('images/' . $student->student_image) }}" width="100" class="img-thumbnail" />
					<input type="hidden" name="hidden_student_image" value="{{ $student->student_image }}" />
				</div>
			</div>
			<div class="text-center">
				<input type="hidden" name="hidden_id" value="{{ $student->id }}" />
				<input type="submit" class="btn btn-primary" value="Edit" />
			</div>	
		</form>
	</div>
</div>
<script>
document.getElementsByName('student_gender')[0].value = "{{ $student->student_gender }}";
</script>

@endsection('content')


Step 7 - Set Resource Route


Under this step, we have to add resource route for student crud application. So for set route, we have to open routes/web.php file and under this file, we have to define resource route for Laravel 9 CRUD Application.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});


Route::resource('students', StudentController::class);


After adding above code, then it will set route for all method of StudentController.php file.

Step 8 - Run Laravel 9 CRUD Application


When we have follow all above steps, that means our Laravel 9 CRUD Application is ready for check output in the browser. So for check output in the browser, first we need to start Laravel 9 Application server, so for this, we have go to command prompt and run following command.


php artisan serve


So this command will start Laravel server and provide us base url of our Laravel 9 CRUD Application. So we have goes to browser, and type give below URL and view output of Laravel 9 CRUD Application.


http://127.0.0.1:8000/students


So this is complete step by step tutorial on Laravel 9 CRUD Application, so you have follow all above steps then you can able to learn How to perform Insert, Update, Delete and Read MySQL Data Operation in Laravel 9 framework and build CRUD Application Laravel 9 framework with MySQL database and Bootstrap 5 Library.

Laravel 9 CRUD Application Video Tutorial


1 - Load MySQL Data in HTML Table with Pagination Links



2 - Insert or Add Data into MySQL Table



3 - Retrieve MySQL Data & Display on Web page



4 - Update or Edit MySQL Data



5 - Delete or Remove Data From MySQL



Monday, 25 March 2019

Step by Step CRUD Operation in Laravel 5.8 with File Upload

Part 1 - Introduction




Part 2 - Fetch and Display Data




Part 3 - Insert or Add Data with File Upload



Part 4 - Fetch Single Data from Database



Part 5 - Edit or Update Existing MySQL Data



Part 6 - Delete data from Database




If you want to learn How can we do CRUD(Create, Read, Update, Delete) operation with upload file in new version of Laravel 5.8. So, from this post, you can find step by step process of doing CRUD with Mysql database from Laravel 5.8 application. For do CRUD in Laravel 5.8, first you have to upgrade your Laravel framework. For upgrade Laravel you have to go to this Laravel Upgrade Link. Contributors of Laravel has continue improvement in Laravel every version. So, in Laravel 5.8 version you can find something new as from Laravel 5.7. There are following new feature introduced in Laravel 5.8.

  • has-one-through Eloquent relationships.
  • Improved email validation.
  • convention-based automatic registration of authorization policies.
  • DynamoDB cache and session drivers.
  • Improved scheduler timezone configuration.
  • Support for assigning multiple authentication guards to broadcast channels.
  • PSR-16 cache driver compliance, improvements to the artisan serve command.
  • PHPUnit 8.0 support.
  • Carbon 2.0 support.
  • Pheanstalk 4.0 support, and a variety of other bug fixes and usability improvements.

If you want to get detailed information on Laravel 5.8, then you have go to this Laravel 5.8 relase Link.

Laravel 5.8 Server Requirements


If you want to use Laravel 5.8 for your web development, first you have to check what is minimum server requirement for using Laravel 5.8. Below you can find Laravel 5.8 server requirement.

  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
  • BCMath PHP Extension

Suppose you have check all above server requirement, and you have all above requirement, then you can start using Laravel 5.8 framework version. So, here first we will make simple CRUD Application in Laravel 5.8, for this you have to following steps.


Step by Step CRUD Operation in Laravel 5.8 with File Upload


Step 1 - Download Laravel 5.8


In first step you have to download Laravel 5.8 version. For this you have to go to command prompt, in which first you have go to your folder path in which you want to download Laravel 5.8. After this you have to run "composer" command, because all Laravel depository handle by composer. After run "composer" command. You have to run following command.


composer create-project laravel/laravel=5.8 crud --prefer-dist


Above command will make crud folder and under this folder it will download Laravel 5.8.

Step 2 - Mysql Database connection Laravel 5.8


Once you have download Laravel 5.8, so now first we want to make Mysql database connection from Laravel 5.8. You can make Mysql database connection from two way.

In first way you have to find .env file in your Laravel 5.8 folder. Open that file and under you have to define your mysql database configuration like below.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


In second way, you have to open config/database.php file, and under this file you can also define your mysql database configuration.


'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]),
        ],


After defining above details you can make Mysql database connection from your Laravel 5.8 application.

Step 3 - Migrate Table from Laravel 5.8 to Mysql Database


In Laravel framework, you have facility from make table in Mysql database from your Laravel application. For this first you have to create migration file in your Laravel folder. For this you have to write following command in your command prompt.


php artisan make:migration create_crud_table --create=crud


This command will create migration file in database/migrations folder. In this file we have to define table column which we want to create in table. Below you can find migration file in which we have define table column.


<?php

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

class CreateCrudTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('image');
            $table->timestamps();
        });
    }

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


Now we want to migrate this table definition from this Laravel application to mysql database. For this we have write following command in command prompt. This command will make crud table in mysql database for perform CRUD operation from Laravel 5.8 application.


php artisan migrate


Step 4 - Create Model file in Laravel 5.8


In this we will seen how can we make model file in Laravel 5.8. This class file mainly used for do database related operation in controller class. For create model files we have to write following command in command prompt.


php artisan make:model Crud -m


This command will make Crud.php model file in app folder. In this file we have to define table column name which you can see below source code of Crud.php file.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Crud extends Model
{
    protected $fillable = [
     'first_name', 'last_name', 'image'
    ];
}





Step 5 - Create Controllers in Laravel 5.8


Controllers files mainly used for handle http request in Laravel 5.8 application. Here we want to create Laravel 5.8 crud controller. For this we have to go to command prompt and under this we have write following command.


php artisan make:controller CrudsController --resource


This command will make CrudsController.php file in app/Http/Controllers folder. Once you have open this file, then you can find all predefine method for do CRUD operation in this controller file. We have to just add code for do particular operation. Below you can find CRUD controller file code below.


<?php

namespace App\Http\Controllers;
use App\Crud;
use Illuminate\Http\Request;

class CrudsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Crud::latest()->paginate(5);
        return view('index', compact('data'))
                ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'image'         =>  'required|image|max:2048'
        ]);

        $image = $request->file('image');

        $new_name = rand() . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('images'), $new_name);
        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $new_name
        );

        Crud::create($form_data);

        return redirect('crud')->with('success', 'Data Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Crud::findOrFail($id);
        return view('view', compact('data'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Crud::findOrFail($id);
        return view('edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $image_name = $request->hidden_image;
        $image = $request->file('image');
        if($image != '')
        {
            $request->validate([
                'first_name'    =>  'required',
                'last_name'     =>  'required',
                'image'         =>  'image|max:2048'
            ]);

            $image_name = rand() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $image_name);
        }
        else
        {
            $request->validate([
                'first_name'    =>  'required',
                'last_name'     =>  'required'
            ]);
        }

        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $image_name
        );
  
        Crud::whereId($id)->update($form_data);

        return redirect('crud')->with('success', 'Data is successfully updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = Crud::findOrFail($id);
        $data->delete();

        return redirect('crud')->with('success', 'Data is successfully deleted');
    }
}


index() - In Laravel Crud controller index() method is a root method of crud controller, so when in browser we have enter base url with controller name, then it will called this index() method. Under this method we will write code for display data from mysql database. In this code it will first fetch data from crud table and store under $data variable, after this we want to make paginate link by using paginate() method in Laravel 5.8. For send data to view file, for this we have use view() method for send data to view file. Source code you can find under index() method.

create() - This method has been used for load create.blade.php file. In this file user can find form for insert new records and filling data insert data request will be send to store() method of CrudsController.php controller class.

store() - This method has received add or insert new records request received from create() method. In this method, it will perform two operation. One is for upload image file by using move() method and second is for insert records into mysql table by using model class. Before upload of image, it will rename image name. After successfully insert or add of data in mysql table from this Laravel 5.8 application, page will redirect to index() method with success message.

show() - This method in Crud controller has been used for fetch single data details based on on value of $id argument. For this it has been used findOrFail() method. After fetch details it will send to view.blade.php file.

edit() - This method main function is fetch single data from Mysql database and load into edit or update form for make required changes.

update() - Update method has received edit or update data request from edit(). This method has done two function like upload of profile image with update or edit mysql data in Laravel 5.8 framework.

delete() - Delete() method mainly used for remove single or multiple data from Mysql Database. This is last operation Crud Operation in Laravel 5.8 Crud tutorial series.




Step 6 - Set Route in Laravel 5.8


This is very useful step in Laravel 5.8, because here we want to set route of all CrudsController class method. For this we have to open to routes/web.php file. In this file we have to write following code for set route of all method.


Route::resource('crud','CrudsController');


Step 7 - Set Data in View File in Laravel 5.8


This is the last step in Laravel 5.8 Crud application, and in this step we have to set data in view file which has been store under resources/views folder, because this view file has received data from controller method, so here we have to set data in view file. Below you can file all view file which has been used in Crud application, and you can also find how data has been set and how to make form in Laravel 5.8 view file.

resources/views/parent.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 Crud Tutorial</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 Crud Tutorial</h3>
     <br />
     @yield('main')
    </div>
 </body>
</html>


resources/views/index.blade.php

@extends('parent')

@section('main')

<table class="table table-bordered table-striped">
 <tr>
  <th width="10%">Image</th>
  <th width="35%">First Name</th>
  <th width="35%">Last Name</th>
  <th width="30%">Action</th>
 </tr>
 @foreach($data as $row)
  <tr>
   <td><img src="{{ URL::to('/') }}/images/{{ $row->image }}" class="img-thumbnail" width="75" /></td>
   <td>{{ $row->first_name }}</td>
   <td>{{ $row->last_name }}</td>
   <td>
    
   </td>
  </tr>
 @endforeach
</table>
{!! $data->links() !!}
@endsection


resources/views/create.blade.php

@extends('parent')

@section('main')
@if($errors->any())
<div class="alert alert-danger">
 <ul>
  @foreach($errors->all() as $error)
  <li>{{ $error }}</li>
  @endforeach
 </ul>
</div>
@endif
<div align="right">
 <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
</div>

<form method="post" action="{{ route('crud.store') }}" enctype="multipart/form-data">

 @csrf
 <div class="form-group">
  <label class="col-md-4 text-right">Enter First Name</label>
  <div class="col-md-8">
   <input type="text" name="first_name" class="form-control input-lg" />
  </div>
 </div>
 <br />
 <br />
 <br />
 <div class="form-group">
  <label class="col-md-4 text-right">Enter Last Name</label>
  <div class="col-md-8">
   <input type="text" name="last_name" class="form-control input-lg" />
  </div>
 </div>
 <br />
 <br />
 <br />
 <div class="form-group">
  <label class="col-md-4 text-right">Select Profile Image</label>
  <div class="col-md-8">
   <input type="file" name="image" />
  </div>
 </div>
 <br /><br /><br />
 <div class="form-group text-center">
  <input type="submit" name="add" class="btn btn-primary input-lg" value="Add" />
 </div>

</form>

@endsection


resources/views/view.blade.php

@extends('parent')

@section('main')

<div class="jumbotron text-center">
 <div align="right">
  <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
 </div>
 <br />
 <img src="{{ URL::to('/') }}/images/{{ $data->image }}" class="img-thumbnail" />
 <h3>First Name - {{ $data->first_name }} </h3>
 <h3>Last Name - {{ $data->last_name }}</h3>
</div>
@endsection


resources/views/edit.blade.php

@extends('parent')

@section('main')
            
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div align="right">
                <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
            </div>
            <br />
     <form method="post" action="{{ route('crud.update', $data->id) }}" enctype="multipart/form-data">
                @csrf
                @method('PATCH')
      <div class="form-group">
       <label class="col-md-4 text-right">Enter First Name</label>
       <div class="col-md-8">
        <input type="text" name="first_name" value="{{ $data->first_name }}" class="form-control input-lg" />
       </div>
      </div>
      <br />
      <br />
      <br />
      <div class="form-group">
       <label class="col-md-4 text-right">Enter Last Name</label>
       <div class="col-md-8">
        <input type="text" name="last_name" value="{{ $data->last_name }}" class="form-control input-lg" />
       </div>
      </div>
      <br />
      <br />
      <br />
      <div class="form-group">
       <label class="col-md-4 text-right">Select Profile Image</label>
       <div class="col-md-8">
        <input type="file" name="image" />
              <img src="{{ URL::to('/') }}/images/{{ $data->image }}" class="img-thumbnail" width="100" />
                        <input type="hidden" name="hidden_image" value="{{ $data->image }}" />
       </div>
      </div>
      <br /><br /><br />
      <div class="form-group text-center">
       <input type="submit" name="edit" class="btn btn-primary input-lg" value="Edit" />
      </div>
     </form>

@endsection


Step 8 - Run Laravel 5.8 Application


Lastly, we want to run Laravel 5.8 Crud application, for this we have to go to command prompt, and write following command.


php artisan serve


Above command will start Laravel 5.8 application. For run Larave 5.8 crud file, you have to write this url http://127.0.0.1:8000/crud in your browser for test code is working or not.

Here will make simple CRUD application with uploading file in Laravel 5.8 version.





Thursday, 13 December 2018

Live Table Add Edit Delete in Laravel using Ajax jQuery

Live Table Add Edit Delete in Laravel using Ajax jQuery - 1




Live Table Add Edit Delete in Laravel using Ajax jQuery - 2




Live Table Add Edit Delete in Laravel using Ajax jQuery - 3




Live Table Add Edit Delete in Laravel using Ajax jQuery - 4





If you are looking for web tutorial on how to make live table application in Laravel framework by using Ajax and jQuery. So, you are come on right place, here you can find step by step by not only web tutorial but also video tutorial on Live table Insert Update Delete mysql table records in Laravel framework with Ajax and jQuery. We all know Laravel is a robust PHP framework for develop enterprise level application from scratch with write small PHP code and reuse same code. If we have use Ajax jQuery with Laravel, then it will make standard level web application.

In this post we have make Single page Live table or Inline table application in Laravel by using Ajax jQuery. In this application we will perform all CRUD operation like Create, Read, Update and Delete mysql database data from Laravel Live table or Inline table application. In this application use can Create or Add or Insert new data into mysql table from table, User can Update or edit exisiting records of Mysql table from this Laravel Live table. User can delete or remove mysql data from this Application. He can perform all this operation without going to other page, but from single html table he can perform all CRUD operation. That means here we will make Single page Live table crud application in Laravel using Ajax and jQuery.

Most of the application there main function is insert, update, delete and read mysql data. So, here we have make Single page Inline table application in Laravel with Ajax jquery, and perform all function from single page without refresh of web page. So, it will increase the speed of your web application, and it will also advance feature in your application. It will improve your application efficiency also. So, if Laravel framework will work with Ajax and jQuery, then it will increase your web presense user interface from user also. Below you can find step by step source code of Live table insert update delete mysql data using Ajax jQuery in Laravel framework.






Source Code


First we have to create Livetable controller, for this we have to go command prompt, and write following command, this command will create LiveTable.php controller file under app/HTTP/controllers folder.


php artisan make:controller LiveTable


Livetable.php


Once controller has been created under app/HTTP/controllers folder. In this class you can find following method for handle HTTP request of Live table crud operation in Laravel.

index() - This is the root method of this class, it will load live_table.blade.php view file in browser, once this live table controller has been called in browser.

fetch_data() - This method has receieved ajax request for fetch data from live_table.blade.php file, and this function return data in json format.

add_data() - This method has received ajax request for insert or add new records in mysql table from live_table.blade.php file, and this method return response once data has been successfully inserted.

update_data() - This method is used for update or edit mysql table records using Ajax. Ajax request has been send from view file to this method for edit or update existing of data of Mysql in Laravel using Ajax.

delete_data() - This method has received delete mysql table data request from Ajax, This method mainly used for delete or remove data operation in Laravel. Once this method has delete data then it send back response to Ajax request.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveTable extends Controller
{
    function index()
    {
        return view('live_table');
    }

    function fetch_data(Request $request)
    {
        if($request->ajax())
        {
            $data = DB::table('tbl_sample')->orderBy('id','desc')->get();
            echo json_encode($data);
        }
    }

    function add_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                'first_name'    =>  $request->first_name,
                'last_name'     =>  $request->last_name
            );
            $id = DB::table('tbl_sample')->insert($data);
            if($id > 0)
            {
                echo '<div class="alert alert-success">Data Inserted</div>';
            }
        } 
    }

    function update_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                $request->column_name       =>  $request->column_value
            );
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->update($data);
            echo '<div class="alert alert-success">Data Updated</div>';
        }
    }

    function delete_data(Request $request)
    {
        if($request->ajax())
        {
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->delete();
            echo '<div class="alert alert-success">Data Deleted</div>';
        }
    }
}
?>





livetable.blade.php


This is view file of Live table application in Laravel and this file you can find under resources/view/livetable.blade.php. This file is used for display output on browser. In this view file you can find html, jquery and Ajax source code for fetch and insert data into mysql table in Laravel. For fetch data using Ajax, here we have make fetch_data() jQuery function which send Ajax request to LiveTable.php controller. For Insert, Update and delete mysql data using Ajax also, here you can find jQuery code in which Ajax request has been send to LiveTable.php controller class.


<!DOCTYPE html>
<html>
 <head>
  <title>Live Table Insert Update Delete in Laravel using Ajax jQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Live Table Insert Update Delete in Laravel using Ajax jQuery</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">Sample Data</div>
    <div class="panel-body">
     <div id="message"></div>
     <div class="table-responsive">
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Delete</th>
        </tr>
       </thead>
       <tbody>
       
       </tbody>
      </table>
      {{ csrf_field() }}
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"/livetable/fetch_data",
   dataType:"json",
   success:function(data)
   {
    var html = '';
    html += '<tr>';
    html += '<td contenteditable id="first_name"></td>';
    html += '<td contenteditable id="last_name"></td>';
    html += '<td><button type="button" class="btn btn-success btn-xs" id="add">Add</button></td></tr>';
    for(var count=0; count < data.length; count++)
    {
     html +='<tr>';
     html +='<td contenteditable class="column_name" data-column_name="first_name" data-id="'+data[count].id+'">'+data[count].first_name+'</td>';
     html += '<td contenteditable class="column_name" data-column_name="last_name" data-id="'+data[count].id+'">'+data[count].last_name+'</td>';
     html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button></td></tr>';
    }
    $('tbody').html(html);
   }
  });
 }

 var _token = $('input[name="_token"]').val();

 $(document).on('click', '#add', function(){
  var first_name = $('#first_name').text();
  var last_name = $('#last_name').text();
  if(first_name != '' && last_name != '')
  {
   $.ajax({
    url:"{{ route('livetable.add_data') }}",
    method:"POST",
    data:{first_name:first_name, last_name:last_name, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
  }
 });

 $(document).on('blur', '.column_name', function(){
  var column_name = $(this).data("column_name");
  var column_value = $(this).text();
  var id = $(this).data("id");
  
  if(column_value != '')
  {
   $.ajax({
    url:"{{ route('livetable.update_data') }}",
    method:"POST",
    data:{column_name:column_name, column_value:column_value, id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
    }
   })
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Enter some value</div>");
  }
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  if(confirm("Are you sure you want to delete this records?"))
  {
   $.ajax({
    url:"{{ route('livetable.delete_data') }}",
    method:"POST",
    data:{id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
 });


});
</script>


web.php


Once you have completed working on Controller class code and view file code, lastly you have to set route for LiveTable.php controller class. In this class we have create index(), fetch_data(), add_data(), update_data() and delete_data() method for fetch, insert and update data using Ajax in Laravel. For set route in Laravel, we have to go to routes/web.php file. And in this file we have to write following code for set route.


Route::get('/livetable', 'LiveTable@index');
Route::get('/livetable/fetch_data', 'LiveTable@fetch_data');
Route::post('/livetable/add_data', 'LiveTable@add_data')->name('livetable.add_data');
Route::post('/livetable/update_data', 'LiveTable@update_data')->name('livetable.update_data');
Route::post('/livetable/delete_data', 'LiveTable@delete_data')->name('livetable.delete_data');


Lastly for run Laravel Live table add edit delete mysql data application using Ajax jQuery, we have to go to command prompt, and write following command.


php artisan serve


Once this command has been run under command prompt in which you have already run composer command, then you will provide you this http://127.0.0.1:8000 link, and just run following link for run Live table application.


http://127.0.0.1:8000/livetable