Laravel Starter Guide: Part 4 – Laravel CRUD Application (Update, Destroy)

Laravel Starter Guide: Part 4 – Laravel CRUD Application (Update, Destroy)

Laravel is a FREE, Open-Source PHP Web Framework. It is created by Taylor Otwell. It follows the Model, View, Controller (MVC) architecture. The websites built in Laravel also secure. It prevents the many attacks that can take place on the website. In this tutorialwe focus on Laravel basic concepts (CRUD) – Update and Destroy

Laravel Starter Guide: Laravel Tutorial (Part 1)
Laravel Starter Guide: Part 2 – Basic Concept (MVC)
Laravel Starter Guide: Part 3 – Laravel CRUD Application (Create & Read)

What is CRUD?

CREATE – READ – UPDATE – DESTROY

Create and Read

Part 1 – Laravel Starter Guide: Part 3 – Laravel CRUD Application (Create & Read)

Update


URL:
 localhost/posts/{id}/edit [PATCH]
Controller Function: edit()
View File: resources/views/posts/edit.blade.php

Update PostController (app/http/controller/PostController.php)

...
...
/**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);

        // show the edit form and pass the data
         return view('posts.edit')->withPost($post);
    }
...
...
laravel crud update destroy

posts/edit.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Create a new Post</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-2"> </div>
            <div class="col-md-8">
                <h1 class="text-primary center"> Update Post {{ $post->id }}</h1>
            </div>
            <div class="col-md-2"> </div>
        </div>
        <br/>

        <div class="row">
            @if ($errors->any())
            <div class="row alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
        </div>

        <div class="row">
            <div class="col-md-2"> </div>
            <div class="col-md-8 col-md-offset-2">
                <form method="POST" action="{{ route('posts.update', $post->id) }}">
                @method('PATCH')
                @csrf
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" name="title" class="form-control" id="title" placeholder="Enter post Title" value={{ $post->title }}>
                    </div>
                    <div class="form-group">
                        <label>Content</label>
                        <textarea class="form-control" name="content" id="content" rows="8">{{ $post->content }}</textarea>
                    </div>
                    <div class="form-group">
                        <label>Link</label>
                        <input type="text" name="link" class="form-control" id="link" placeholder="" value={{ $post->link }}>
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
            <div class="col-md-2"> </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
laravel crud update destroy
laravel crud

Store the data (Update)

URL: localhost/update [PUT]
Controller Function: update()
View File: no view

Update PostController (app/http/controller/PostController.php)

#1 – Validate the data

$this->validate($request, array(
    'title'   => 'required|max:100',
    'content' => 'required',
    'link'    => 'required'
));

#2 – Store in the database

//Store in the database
$post = Post::find($id);

$post->title = $request->title;
$post->content = $request->content;
$post->link = $request->link;

$post->save();

#3 – Redirect – posts/{id}

return redirect()->route('posts.show', $post->id);

Complete code

...
...
/**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, array(
            'title'   => 'required|max:100',
            'content' => 'required',
            'link'    => 'required'
        ));

        //Store in the database
        $post = Post::find($id);

        $post->title = $request->title;
        $post->content = $request->content;
        $post->link = $request->link;

        $post->save();

        return redirect()->route('posts.show', $post->id);
    }
...
...
laravel crud
laravel crud

Add action to the edit button

Update posts/show.blade.php – change following code and save

laravel crud update destroy
Old code
<button type="" class="btn btn-primary">Edit</button>
....
New Code
<a href="{{ route('posts.edit', $post->id) }}" class="btn btn-primary">Edit</a>
....

Destroy


URL:
 localhost/posts/{id} [DELETE]
Controller Function:  destroy()
View File: no view

Update PostController (app/http/controller/PostController.php)

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

        return redirect('/posts');
    }
...
...

Add action to the delete button

Update posts/show.blade.php – change following code and save

laravel crud update destroy
Old code
<button type="" class="btn btn-danger">Delete</button>
....
New Code
<form action="{{ route('posts.destroy', $post->id)}}" method="POST">
    @csrf
    @method('DELETE')
    <button type="submit" class="btn btn-danger">Delete</button>
 </form>
....


Sources : 
https://pixabay.com/ (images) 
https://laravel.com/docs/5.8/ (Documentation)

Hello Friends,

Hope this post (Laravel Starter Guide: Laravel Tutorial Basic (Part 4) – Laravel CRUD: Update and Destroy) will help you to learn something, If you enjoy my work then please share my posts with your friends and anyone who might be interested in programming and web developing. Please don’t forget to subscribe to my mailing list.

If you had any problem with this post, please do mention it in the comment section.

Like CtechF Facebook fan page: https://www.facebook.com/ctechf

What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python
Python Tutorial: Django Tutorial for Beginners

What is HTML?

HTML (HyperText Markup Language) is developed by Tim Berners-Lee. An HTML document which can be displayed through a web browser is called a web page. HTML is not a computer language it’s a markup language.

For more information: HTML Tutorial: Introduction for beginners (Basic)

What is PHP?

PHP: Hypertext Preprocessor is a general-purpose server-side script language. it designed for web development. It designed by Rasmus Lerdorf in 1994 and first released in 1995. PHP is free to download and use. It can contain text, HTML, JavaScript, CSS and PHP code. it runs on Windows, Linux, Mac OS and etc… PHP can do many things such as generate dynamic web pages, manage data in your database, control user access, etc… PHP 7 is much faster than the previous versions. In this tutorial. You will learn to install and run PHP on Windows pc.

For more information
PHP 7 Tutorial: Introduction for Beginners (Basic)
PHP7 Tutorial | Part 2 – GET, POST and Cookies
PHP7 Tutorial | Part 3 – MySQL and PHP

What is SQL?

SQL (Structured Query Language) is a standard language for storing, managing and retrieving data in databases. SQL was developed at IBM by Donald Chamberlin and Raymond Boyce. and first released in 1991. SQL became a standard of the ANSI (American National Standards Institute) in 1986.

For more information: SQL Tutorial: Introduction for beginners (Basic)

How to be a Programmer

Liked it? Take a second to support CtechF on Patreon!

Leave a Reply

81 Shares
Share
Tweet
Share
Pin
Share