Laravel 8 CRUD Example | Laravel 8 Tutorial

Laravel 8 CRUD Example | Laravel 8 Tutorial

 

Laravel 8 CRUD Example | Laravel 8 Tutorial 

Today in this tutorial we learn Laravel 8 CRUD App Example Tutorial from basic Step by step. CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation for databases. This post contains a Laravel crud application that will perform all these operations on a MySQL database table in one place. We have explained the Laravel 8 crud operation where we have updated in the easy and best way to learn create, update, delete, edit with the database. Before starting to Laravel 8 from scratch a beginner must need to understand Controller, routes, modal, migrations, and theme layouts creation in Laravel. If you already learn all about let’s start with Laravel 8 CRUD Example step-by-step process from basic.


Step 1: Install Laravel 8 App

First, create a new Laravel 8 project adding the following command in the terminal.

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

Step 2: Configure the MySQL Database

Now, you need to create the MySQL database and connect that database to the Laravel application. Open your localhost/PHPMyAdmin and add a new database name then add the credentials in the .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 the MySQL database.

Step 3: Create a Model and Migration File

Now generate model and migration file just adding the below command in your terminal which generates a model file and migration which will show your database table after running the migration command.

php artisan make:model Student -m

Now you can see in your database migration directory created a new file the same as below, here you need to add your database columns.

database\migrations\2020_10_19_134839_create_students_table.php

<?php

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

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

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

After adding the columns now run the below command which is generated a table in your database.

php artisan migrate

Add Fillable Property: In your app/models inside generated a new file Post.php file where you need to add fillable properties.

app\Models\Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
      'title', 'description'
    ];
}

Step 5: Add Resources routes

In Laravel 8 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 the same as below.

routes/web.php

<?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::get('create', 'App\Http\Controllers\StudentController@create')->name('student.create');
Route::post('store', 'App\Http\Controllers\StudentController@store')->name('student.store');
Route::get('list', 'App\Http\Controllers\StudentController@index')->name('student.list');
Route::post('update', 'App\Http\Controllers\StudentController@update')->name('student.update');
Route::get('show', 'App\Http\Controllers\StudentController@show')->name('student.show');
Route::get('edit', 'App\Http\Controllers\StudentController@edit')->name('student.edit');
Route::get('destroy{id}', 'App\Http\Controllers\StudentController@destroy')->name('student.destroy');

Step 6: Create a controller

Now you need to create a controller just adding the below command and generate a new resource controller PostController.

php artisan make:controller StudentConroller --resource

After running this command you will find a new file in this path “app/Http/Controllers/PostController.php”. Where you saw here already created methods the same as below. Now you need to put the below codes on your functions.

1) index() => this method get your all data from database.

2) create() => this method work creating new post.

3) store() => this method store data in your database.

3) show() => this method show the record.

3) edit() => Using this method we can edit our post.

3) update() => update method to updating the post.

7) destroy() => Using this method’s we can delete our record.

So, open your PostController.php file and put the below code on it.

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()
    {
        //
        $students = Student::all();
        return view('student.list', compact('students','students'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $request->validate([
            'txtFirstName'=>'required',
            'txtLastName'=> 'required',
            'txtAddress' => 'required'
        ]);

        $student = new Student([
            'first_name' => $request->get('txtFirstName'),
            'last_name'=> $request->get('txtLastName'),
            'address'=> $request->get('txtAddress')
        ]);

        $student->save();
        return redirect()->route('student.create')->with('success', 'Student has been added');
    }

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        //
        $request->validate([
            'txtFirstName'=>'required',
            'txtLastName'=> 'required',
            'txtAddress' => 'required'
        ]);


        $student = Student::find($id);
        $student->first_name = $request->get('txtFirstName');
        $student->last_name = $request->get('txtLastName');
        $student->address = $request->get('txtAddress');

        $student->update();

        return redirect('/student')->with('success', 'Student updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy(Student $student)
    {
        //
        $student->delete();
        return redirect()->route('student.destroy')->with('success', 'Student deleted successfully');
    }
}
?>

Step 7: Create Blade Files

Here in this step, we create our view files. First, create two folders one is “layout” and another is “posts”. In the layout, folder creates an app.blade.php file, and inside the posts folder create another blade file. If you don’t know to integrate our blade files in Laravel then please check first here how to integrate the Laravel bootstrap admin panel.  Now create below blade files for your crud app:

1) layout.blade.php
2) index.blade.php
3) create.blade.php
4) edit.blade.php
5) show.blade.php

So let’s just create the following file and put the bellow code.

resources/views/layout/app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 8 CRUD (Create Read Update Delete) Tutorial For Beginners</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css">



</head>
<body>
<div class="container">
    @yield('content')
</div>
    <script src=" https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#example').DataTable();
        } );
    </script>
</body>
</html>

resources/views/student/create.blade.php

@extends('layout.app')

@section('content')
<br>
    <div class="row">
        <div class="col-lg-11">
            <h2>Add New Student</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-primary" href="{{ route('student.list')}}"> Back</a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <form action="{{ route('student.store') }}" method="POST">
        @csrf
        <div class="form-group">
            <label for="txtFirstName">First Name:</label>
            <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
        </div>
        <div class="form-group">
            <label for="txtLastName">Last Name:</label>
            <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
        </div>
        <div class="form-group">
            <label for="txtAddress">Address:</label>
            <textarea class="form-control" id="txtAddress" name="txtAddress" rows="3" placeholder="Enter Address"></textarea>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
    </form>
@endsection

resources/views/student/list.blade.php

@extends('layout.app')

@section('content')
<br>
    <div class="row">
        <div class="col-lg-11">
                <h2>Laravel 8 CRUD Example</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-success" href="{{ route('student.create') }}">Add</a>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
    <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Adddress</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        @foreach ($students as $student)
            <tr>
                <td>{{ $student->id }}</td>
                <td>{{ $student->first_name }}</td>
                <td>{{ $student->last_name }}</td>
                <td>{{ $student->address }}</td>
                <td>
                    <form action="{{ route('student.destroy',['id'=>$student->id])}}"  method="POST"onsubmit="return confirm('Are you sure you want to unenroll?');" style="display: inline-block;">
                        <a class="btn btn-info btn-sm" href="{{ route('student.show',$student->id) }}">Show</a>
                        <a class="btn btn-primary btn-sm" href="{{ route('student.edit',$student->id) }}">Edit</a>
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                    </form>
                </td>
            </tr>
        @endforeach

        </tbody>
    </table>

@endsection

resources/views/student/edit.blade.php

@extends('layout.app')

@section('content')
<br>
    <div class="row">
        <div class="col-lg-11">
            <h2>Update Student</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-primary" href="{{ route('student.create') }}"> Back</a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <form method="post" action="{{ route('student.update',$student->id) }}" >
        @method('PATCH')
        @csrf
        <div class="form-group">
            <label for="txtFirstName">First Name:</label>
            <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName" value="{{ $student->first_name }}">
        </div>
        <div class="form-group">
            <label for="txtLastName">Last Name:</label>
            <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName" value="{{ $student->last_name }}">
        </div>
        <div class="form-group">
            <label for="txtAddress">Address:</label>
            <textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address">{{ $student->address }}</textarea>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
    </form>
@endsection

resources/views/student/view.blade.php

@extends('layout.app')

@section('content')
    <div class="row">
        <div class="col-lg-11">
                <h2>Laravel 8 CRUD Example</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-primary" href="{{ route('student.list') }}"> Back</a>
        </div>
    </div>
    <table class="table table-bordered">
        <tr>
            <th>First Name:</th>
            <td>{{ $student->first_name }}</td>
        </tr>
        <tr>
            <th>Last Name:</th>
            <td>{{ $student->first_name }}</td>
        </tr>
        <tr>
            <th>Address:</th>
            <td>{{ $student->address }}</td>
        </tr>

    </table>
@endsection

Finally, Laravel 7.0 CRUD Example Tutorial For Beginners From Scratch is over. In this CRUD app, we used one function to create and edit. Let's run this crud application example with Laravel 7 so run the below command and see in your browser.

php artisan serve

Now you can open the below URL on your browser: http://localhost:8000/create So friends it's a very easy way to Laravel CRUD operation step by step.

Hope this tutorial helps you to Learn Laravel 8 crud tutorial.  If you have any questions regarding the Laravel crud operation generator then please comment below we appreciate your comment.

Reactions

Post a Comment

1 Comments

  1. Hi there,
    first of all thanxs for this nice and quick tutorial. But unfortunately I wasn´t able to coomplete it and see the result. I guess that you probably made some little errors and typos while doing this. Like instruction reagrding PostController vs-StudentController and the other things is this:
    Step 7: Create Blade Files
    Here in this step, we create our view files. First, create two folders one is “layout” and another is “posts”. In the layout, folder creates an app.blade.php file, and inside the posts folder create another blade file. If you don’t know to integrate our blade files in Laravel then please check first here how to integrate the Laravel bootstrap admin panel. Now create below blade files for your crud app:


    layout and posts folder doe go where.


    --> Would be very happy if you could check this and reply&correct these.

    Thanxs :)

    ReplyDelete

CAN FEEDBACK

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)

close