Crud in Laravel 5.5

CRUD (Create Read Update Delete) application in Laravel 5.5 , Laravel crud example

In this post i am going to show you how to create a sample CRUD application in Laravel 5.5 from Scratch.
Laravel is going to release his new version 5.5 in this month, It documentation is released you can read the documentation of Laravel 5.5 from https://laravel.com/docs/5.5/.
Laravel 5.5 will require PHP version >= 7.0.0 with OpenSSL,PDO,Mbstring,Tokenizer,XML PHP Extensions installed on server.
Below are step by step guide to install and create a demo Laravel application to add , delete, view and update youtube videos with title,
description in Laravel.

Steps to create CRUD (Create Read Update Delete) application in Laravel 5.5


Step 1: Installing laravel 5.5

To install Laravel 5.5 please run below on your terminal, we are using Ubuntu 16.04 for this installation.

composer create-project --prefer-dist laravel/laravel Laravel5.5

Step 2 : Configuring files permissions.

Laravel requires read write permission in “storage” and “bootstrap/cache” directories , so change the permissions of these directories by running below commands.

sudo chmod -R 777 storage
 sudo chmod -R 777 bootstrap/cache

Step 3: Configuring database connection

In order to configure your database in Laravel 5.5, Please open .env file. .env file is situated on laravel root folder.




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

Step 4 Creating tables and migartions

php artisan make:migration create_videos_table

Running above command will create a new file in database/migrations directory , open that file and put below code in that

<?php

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

class CreateVideosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('video_title');
            $table->string('video_url');
            $table->text('description');
            $table->tinyInteger('status', 0);
            $table->timestamps();
           
        });
    }

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


After saving above code in file, Run below command to create your table in database.

php artisan migrate

Step 4: Creating your Model Class .

To create a model class in Laravel you can use php artisan make model command followed by model name.
Run below command to create your migration.

php artisan make:model Video

Above command will generate a new file named Video.php in app folder.Open that file put below code in it.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    //
    protected $fillable = ['video_title', 'video_url', 'description'];
}





Step 5: Creating Controller.

You can generate your controller by running php artisan make:controller command.

php artisan make:controller VideoController --resource

Once you have executed the above command a new file name VideoController.php is created in app/Http/Controller directory, open that file and and below code in that.

  

<?php

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

class VideoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
     
       $videos = Video::orderBy('id','DESC')->paginate(5);

       return view('Video.index',compact('videos'));

            
    }

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

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

      $this->validate($request, [

            'video_title' => 'required',

            'video_url' => 'required',

        ]);


        Video::create($request->all());

        return redirect()->route('video.index')

                        ->with('success','Video created successfully');
    }

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

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

        return view('Video.edit',compact('video'));
    }

    /**
     * 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, [

            'video_title' => 'required',

            'video_url' => 'required',

        ]);


        Video::find($id)->update($request->all());

        return redirect()->route('video.index')

                        ->with('success','Video updated successfully');

    }

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

        return redirect()->route('video.index')

                        ->with('success','Video deleted successfully');
    }
}


Step 6 : Configuring routes

In this step we have attach our controller to application route.Open your routes/web.php
add below code in it.

 Route::resource('video','VideoController');

Step 7: Creating layout for your application.

Open resources/view directory and create a new directory named layouts.You can create your layouts directory via command line by running below commnads on terminal;

 cd /resources/views/
 mkdir layouts.

After creating layouts directory create a new file default.blade.php inside that folder add below code in it.


<!DOCTYPE html>
	<html lang="en">
	<head>
	  <meta charset="utf-8">
	  <meta name="viewport"
	     content="width=device-width, initial-scale=1, user-scalable=yes">
	  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
	</head>
	<body>
	 
	<div class="container-fluid" style="margin-top: 100px">

	@yield('content')
	</div>
	 <style type="text/css">
	  .table {
	      border-top: 2px solid #ccc;
	     
	  }

	 </style>
	</body>
</html>

	



Step 8: Creating views files for application

Create a new folder named Video and create following files index.blade.php ,create.blade.php ,edit.blade.php , show.blade.php in that.

index.blade.php


@extends('layouts.default')

 

@section('content')

	<div class="row">

		<section class="content">
			
			<div class="col-md-8 col-md-offset-2">
				<div class="panel panel-default">
					<div class="panel-body">
					<div class="pull-left"><h3>List Videos</h3></div>
						<div class="pull-right">
							<div class="btn-group">
								
								<a href="{{ route('video.create') }}" class="btn btn-info" >Add New</a>
								
							</div>
						</div>
						<div class="table-container">
              <table id="mytable" class="table table-bordred table-striped">
                   
                   <thead>
                   
                       <th><input type="checkbox" id="checkall" /></th>
                       <th>Video Title</th>
                       <th>Video URL</th>
                       <th>Video Description</th>
                       <th>Status</th>
                       <th>View</th>
                       <th>Edit</th>
                       <th>Delete</th>
                   </thead>
    <tbody>
  @if($videos->count())  
  @foreach($videos as $video)  
    <tr>
    <td><input type="checkbox" class="checkthis" /></td>
    <td>{{$video->video_title}}</td>
    <td>{{$video->video_url}}</td>
    <td>{{$video->description}}</td>
    <td> <span class="label label-{{ ($video->status) ? 'success' : 'danger' }}"> {{ ($video->status) ? ' Active ' : 'Inactive' }}</span></td>
    <td><a class="btn btn-primary btn-xs" href="{{action('VideoController@show', $video->id)}}" ><span class="glyphicon glyphicon-eye-open"></span></a></td>
    <td><a class="btn btn-primary btn-xs" href="{{action('VideoController@edit', $video->id)}}" ><span class="glyphicon glyphicon-pencil"></span></a></td>
    <td>
<form action="{{action('VideoController@destroy', $video->id)}}" method="post">
     {{csrf_field()}}
     <input name="_method" type="hidden" value="DELETE">
   
     <button class="btn btn-danger btn-xs" type="submit"><span class="glyphicon glyphicon-trash"></span></button>
    </td>
    </tr>
   @endforeach 
   @else
 <tr>
    <td colspan="7">No Records found !!</td>
    </tr>
   @endif
 
   
    
   
    
    </tbody>
        
</table>
						</div>
					</div>

				</div>
			</div>
		</section>

@endsection


create.blade.php


@extends('layouts.default')

 

@section('content')

	<div class="row">

		<section class="content">

			<div class="col-md-8 col-md-offset-2">
				  @if (count($errors) > 0)

			        <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(Session::has('success'))
				    <div class="alert alert-info">
				      {{Session::get('success')}}
				    </div>
				@endif

				<div class="panel panel-default">
					<div class="panel-heading">
				    		<h3 class="panel-title">Add a Video</h3>
				 	</div>

					<div class="panel-body">
			
					
						<div class="table-container">
    						<form method="POST" action="{{ route('video.store') }}"  role="form">
    						{{ csrf_field() }}
			    			<div class="row">
			    				<div class="col-xs-6 col-sm-6 col-md-6">
			    					<div class="form-group">
			                <input type="text" name="video_title" id="video_title" class="form-control input-sm" placeholder="Video Title">
			    					</div>
			    				</div>
			    				<div class="col-xs-6 col-sm-6 col-md-6">
			    					<div class="form-group">
			    						<input type="text" name="video_url" id="video_url" class="form-control input-sm" placeholder="Video Url">
			    					</div>
			    				</div>
			    			</div>

			    			<div class="form-group">
			    				<textarea name="description" class="form-control input-sm" placeholder="Description"></textarea>
			    			</div>

			    		
			    			
			    		 <div class="row">
							
							<div class="col-xs-12 col-sm-12 col-md-12">
								<input type="submit"  value="Save" class="btn btn-success btn-block">
								<a href="{{ route('video.index') }}" class="btn btn-info btn-block" >Back</a>
							</div>	
							
					     </div>
			    		</form>
						</div>
					</div>

				</div>
			</div>
		</section>

@endsection



edit.blade.php

@extends('layouts.default')

@section('content')

	<div class="row">

		<section class="content">

			<div class="col-md-8 col-md-offset-2">
				  @if (count($errors) > 0)

			        <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(Session::has('success'))
				    <div class="alert alert-info">
				      {{Session::get('success')}}
				    </div>
				@endif

				<div class="panel panel-default">
					<div class="panel-heading">
				    		<h3 class="panel-title">Update Video : {{$video->video_title}}</h3>
				 	</div>

					<div class="panel-body">
			
					
						<div class="table-container">
    						<form method="POST" action="{{ route('video.update', $video->id) }}"  role="form">
    						{{ csrf_field() }}
    						<input name="_method" type="hidden" value="PATCH">
			    			<div class="row">
			    				<div class="col-xs-6 col-sm-6 col-md-6">
			    					<div class="form-group">
			                <input type="text" name="video_title" value="{{$video->video_title}}" id="video_title" class="form-control input-sm" placeholder="Video Title">
			    					</div>
			    				</div>
			    				<div class="col-xs-6 col-sm-6 col-md-6">
			    					<div class="form-group">
			    						<input type="text" name="video_url" value="{{$video->video_url}}" id="video_url" class="form-control input-sm" placeholder="Video Url">
			    					</div>
			    				</div>
			    			</div>

			    			<div class="form-group">
			    				<textarea name="description" class="form-control input-sm" placeholder="Description">{{$video->description}}</textarea>
			    			</div>

			    		
			    			
			    		 <div class="row">
							
							<div class="col-xs-12 col-sm-12 col-md-12">
								<input type="submit"  value="Update" class="btn btn-success btn-block">
								<a href="{{ route('video.index') }}" class="btn btn-info btn-block" >Back</a>
							</div>	
							
					     </div>
			    		</form>
						</div>
					</div>

				</div>
			</div>
		</section>

@endsection

show.blade.php

@extends('layouts.default')

 

@section('content')

<div class="row">

		<section class="content">

			<div class="col-md-8 col-md-offset-2">


				<div class="panel panel-default">
					<div class="panel-heading">
				    		<h3 class="panel-title">{{$video->video_title}}</h3>
				 	</div>

					<div class="panel-body">
			
					
						<div class="table-container">
						<div class="video" style="text-align:center">
						<iframe style="width:100%" height="315" src="{{$video->video_url}}" frameborder="0" allowfullscreen></iframe>
						</div>
						<div class="video">
						{{$video->description}}
						</div>
    		
			    			
			    		 <div class="row">
							
							<div class="col-xs-12 col-sm-12 col-md-12">
								
								<a href="{{ route('video.index') }}" class="btn btn-info btn-block" >Back</a>
							</div>	
							
					     </div>
			    		
						</div>
					</div>

				</div>
			</div>
		</section>



@endsection

Open your browser and point your browser to below Url to preview the app.
localhost/laravel5.5/public/video

Leave a Reply

Your email address will not be published. Required fields are marked *