Laravel Starter Guide: Part 3 – Laravel CRUD Application

laravel crud

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).

Laravel Starter Guide: Laravel Tutorial (Part 1)
Laravel Starter Guide: Part 2 – Basic Concept (MVC)

What is CRUD?

CREATE – READ – UPDATE – DESTROY

Enter the following command to create a controller for the CRUD system.

php artisan make:controller PostController --resource

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Create a route for the CRUD – Update Route (routes/web.php)

Route::resource('posts', 'PostController');

Route List

php artisan route:list

Create

URL: localhost/posts/create [GET]
Controller Function: create()
View File: resources/views/posts/create.blade.php

posts/create.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"> Create a new Post </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="/posts">
                @csrf
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" name="title" class="form-control" id="title" placeholder="Enter post Title">
                    </div>
                    <div class="form-group">
                        <label>Content</label>
                        <textarea class="form-control" name="content" id="content" rows="8"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Link</label>
                        <input type="text" name="link" class="form-control" id="link" placeholder="">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</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>

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

.....
.....

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

.....
.....

The run server and visit http://127.0.0.1/posts/create or http://localhost/posts/create

Store the data

URL: localhost/posts [POST]
Controller Function: store()
View File: no view

#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 = new Post;

$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

use app\Post;
.....
.....

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //Validate the data
    $this->validate($request, array(
        'title'   => 'required|max:100',
        'content' => 'required',
        'link'    => 'required'
    ));

     //Store in the database
     $post = new Post;

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

     $post->save();

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

}

.....
.....

add use app\Post; line for the import post model

Then run the server and add some datas

Print out validation errors

Add following code in your create.blade.php

<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>

Read

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

posts/show.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>Post - {{ $post->id }} </title>
</head>
<body>
    
    <div class="container">
    <br/><br/>
        <div class="row">
            <h1 class="text-primary center"> {{ $post->title }} </h1>
        </div>

        <div class="row">
            <div class="col-md-8 col-md-offset-2">
              <p>  {{ $post->content }} </p>
            </div>
        </div>

        <div class="row">
              <a href="{{ $post->link }}">Read more >>></a>
        </div>

        <br/><br/>
        <div class="row">
            <div class="col-md-4">
                <button type="" class="btn btn-primary">Edit</button>
                <button type="" class="btn btn-danger">Delete</button>
            </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>

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

.....
.....

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $post = Post::find($id);

    return view('posts.show')->withPost($post);
}

.....
.....

Show all Posts

URL: localhost/posts [GET]
Controller Function: index()
View File: resources/views/posts/index.blade.php

posts/index.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>Posts</title>
</head>
<body>
    
    <div class="container">
        <br>
        <div class="row">
            <div class="col-md-8">
                <h1 class="text-danger"> All posts </h1>
            </div>

            <div class="col-md-4">
                <a href="{{ route('posts.create') }}" class="btn btn-lg btn-block btn-primary">Create new Post</a>
            </div>
        </div>
        <hr>
        <br/><br/>

            @foreach ($posts as $post)
                <div class="row">
                    <div class="col-md-12">
                        <h3> {{ $post->title }} </h3>
                        <p> 
                            {{ substr($post->content, 0, 350) }}
                            {{ strlen($post->content) > 350 ? "......" : "" }} 
                        </p>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-2">
                        <a href="{{ route('posts.show', $post->id)  }}" class="btn btn-sm btn-block btn-primary">Read more>></a>
                    </div>
                </div>
                <br/><hr>
            @endforeach
    </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>

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

.....
.....

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $posts = Post::all();
    return view('posts.index')->withPosts($posts);
}

.....
.....
laravel crud


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

Hello Friends,

Hope this post (Laravel Starter Guide: Laravel Tutorial Basic (Part 3)) 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

52 Shares
Share
Tweet
Share
Pin
Share