article

Sunday, April 24, 2022

Python Django Simple CRUD (Create, Read, Update and Delete)

Python Django Simple CRUD (Create, Read, Update and Delete)

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path, include #add include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')), #add this line
]
myapp/urls.py
//myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.PostDetailView.as_view(), name='detail'),
    path('edit/<int:pk>/', views.edit, name='edit'),
    path('post/', views.postview, name='post'),
    path('delete/<int:pk>/', views.delete, name='delete'),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PostForm
from .models import Post
from django.views.generic import ListView, DetailView

class IndexView(ListView):
    template_name='crud/index.html'
    context_object_name = 'post_list'

    def get_queryset(self):
        return Post.objects.all()

class PostDetailView(DetailView):
    model=Post
    template_name = 'crud/post-detail.html'

def postview(request):
    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('index')

    form = PostForm()
    return render(request,'crud/post.html',{'form': form})

def edit(request, pk, template_name='crud/edit.html'):
    post= get_object_or_404(Post, pk=pk)
    form = PostForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        return redirect('index')
    return render(request, template_name, {'form':form})

def delete(request, pk, template_name='crud/confirm_delete.html'):
    post= get_object_or_404(Post, pk=pk)    
    if request.method=='POST':
        post.delete()
        return redirect('index')
    return render(request, template_name, {'object':post})
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=120, help_text='title of message.')
    message = models.TextField(help_text="what's on your mind ...")
 
    def __str__(self):
        return self.title
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Table Created Check Database table
myapp/forms.py
 
//myapp/forms.py
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = "__all__"
myapp/templates/crud/base.html
 
//myapp/templates/crud/base.html
<!DOCTYPE html>
<html>
<head>
<title>CRUD app</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>	
myapp/templates/crud/index.html
 
//myapp/templates/crud/index.html
{% extends 'crud/base.html' %}

{% block content %}
<div class="container">
	<div class="row">
		<h1>Python Django CRUD (Create, Read, Update and Delete)</h1>
	</div>
    <div class="row">
        <div class="col-md-12">
            <h2>Post Table
				<a href="{% url 'post' %}"><button type="button" class="btn btn-success">Add New</button></a>
            </h2>
            <table class="table table-bordered table-striped">
                <thead>
                    <th>Title</th>
                    <th>Action</th>
                </thead>
                <tbody>
					{% for post in post_list %}
                        <tr>
                            <td><a href="{% url 'detail' post.pk %}">{{ post.title }}</a>  <span class="badge"></span></td>
                            <td>
								<a href="{% url 'detail' post.pk %}"><button type="button" class="btn btn-info">View</button></a> |
								<a href="{% url 'edit' post.pk %}"><button type="button" class="btn btn-info">Edit</button></a> |
								<a href="{% url 'delete' post.pk %}"><button type="button" class="btn btn-danger">Delete</button></a>
							</td>
                        </tr>
					{% endfor %}	
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}
we will be using django-widget-tweaks install it https://pypi.org/project/django-widget-tweaks/
pip install django-widget-tweaks
C:\my_project_django\testdev>pip install django-widget-tweaks
open settings.py INSTALLED_APPS section and add widget_tweaks myapp/templates/crud/post.html
 
//myapp/templates/crud/post.html
{% extends 'crud/base.html' %}

{% load widget_tweaks %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-10">
			<h6 style="text-align:center;"><font color="red"> All fields are required</font> </h6>
		</div>
		<div class="col-10">
			<form method="post" novalidate>
				{% csrf_token %}
				{% for hidden_field in form.hidden_fields %}
					   {{ hidden_field }}
					 {% endfor %}
				{% for field in form.visible_fields %}
				<div class="form-group">
				 {{ field.label_tag }}
				 {% render_field field class="form-control" %}
				 {% if field.help_text %}
					<small class="form-text text-muted">{{ field.help_text }}</small>
				 {% endif %}
				</div>
				{% endfor %}
			<button type="submit" class="btn btn-primary">Add New Post</button>
		    </form>
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/post-detail.html
 
//myapp/templates/crud/post-detail.html
{% extends 'crud/base.html' %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-8">
			<p class="h2">{{post.title}}</p>
		</div>
		<div class="col-4">
		  	<a href="/"><button type="button" class="btn btn-info">Back</button></a> |
		  	<a href="{% url 'edit' post.pk %}"><button type="button" class="btn btn-info">Edit</button></a> |
			<a href="{% url 'delete' post.pk %}"><button type="button" class="btn btn-danger">Delete</button></a>
		</div>
	</div>
	<div class="row">
		<div class="col-12">
			{{post.message}}
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/edit.html
 
//myapp/templates/crud/edit.html
{% extends 'crud/base.html' %}

{% load widget_tweaks %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-10">
			<h6 style="text-align:center;"><font color="red"> All fields are required</font> </h6>
		</div>
		<div class="col-10">
	   <form method="post" novalidate>
			{% csrf_token %}
			{% for hidden_field in form.hidden_fields %}
				   {{ hidden_field }}
				 {% endfor %}
			{% for field in form.visible_fields %}
				   <div class="form-group">
					 {{ field.label_tag }}
					 {% render_field field class="form-control" %}
					 {% if field.help_text %}
					   <small class="form-text text-muted">{{ field.help_text }}</small>
					 {% endif %}
				   </div>
				 {% endfor %}
			<button type="submit" class="btn btn-primary">Update Post</button>
		</form>
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/confirm_delete.html
 
//myapp/templates/crud/confirm_delete.html
{% extends 'crud/base.html' %}
{% block content %}
<div class="container" style="padding:20px;">
	<div class="row">
		<div class="col-md-10 col-xs-10 col-sm-10">
			<form method="post">
				{% csrf_token %}
				<div class="form-row">
				  <div class="alert alert-warning">
				   Are you sure you want to delete {{ object }}?
				  </div>
				</div>
				<button type="submit" class="btn btn-danger">Delete</button>
			</form>
		</div>
	</div>
</div>
{% endblock %}
Register App myapp

devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'widget_tweaks', 
]
registered post in admin
and login to admin http://127.0.0.1:8000/admin
 
//myapp/admin.py
from django.contrib import admin
from .models import Post #add this to import the Post model

# Register your models here.
admin.site.register(Post) #add this to register the Post model
Run : C:\my_project_django\testdev>python manage.py runserver

Python Django Upload Multiple Files using jQuery AJAX

Python Django Upload Multiple Files using jQuery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
testdev/urls.py
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.upload_files, name='upload_files'),
	path('upload', views.upload_files, name='upload_files'),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def upload_files(request):
    if request.method == "GET":
        return render(request, 'index.html', )
    if request.method == 'POST':
        files = request.FILES.getlist('files[]', None)
        #print(files)
        for f in files:
            handle_uploaded_file(f)
        return JsonResponse({'msg':'<div class="alert alert-success" role="alert">File successfully uploaded</div>'})
    else:
        return render(request, 'index.html', )
			
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/templates/index.html
 
//myapp/templates/index.html
{% extends 'base.html' %}

{% block body %}
	<div style="width: 500px; margin: auto;">
		<fieldset name="Multiple Files Upload">
			{% if msg %} {% autoescape off %} {{ msg }} {% endautoescape %} {% endif %}
			<div id="msg"></div>
			<p>
				{% csrf_token %}
				<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
				<button id="upload" class="btn btn-primary">Upload</button>
			</p>
		</fieldset>
	</div>
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html>
<head>
<title>Python Django Upload Multiple Files using jQuery AJAX - cairocoders</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django Upload Multiple Files using jQuery AJAX</h3></p>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}
      
        {% endblock %}
    </div>
</div> 
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
	$('#upload').on('click', function () {
		var form_data = new FormData();
		var ins = document.getElementById('multiFiles').files.length;
					
		if(ins == 0) {
			$('#msg').html('<div class="alert alert-danger" role="alert">Select at least one file</div>');
			return;
		}
					
		for (var x = 0; x < ins; x++) {
			form_data.append("files[]", document.getElementById('multiFiles').files[x]);
		}
					
		csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
					
		//console.log(csrf_token);
					
		form_data.append("csrfmiddlewaretoken", csrf_token);
					
		$.ajax({
			url: 'upload', // point to server-side URL
			dataType: 'json', // what to expect back from server
			cache: false,
			contentType: false,
			processData: false,
			//data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token},
			data: form_data,
			type: 'post',
			success: function (response) { // display success response
				$('#msg').html(response.msg);
			},
			error: function (response) {
				$('#msg').html(response.message); // display error response
			}
		});
	});
});
</script>
</body>
</html>
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
Run : C:\my_project_django\testdev>python manage.py runserver

Saturday, April 23, 2022

Laravel 9 Joining Tables Insert Data in Bootstrap 5 Modal

Laravel 9 Joining Tables Insert Data in Bootstrap 5 Modal

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller EmployeeController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller EmployeeController
change it with the following codes:
blog\app\Http\Controllers\EmployeeController.php
//blog\app\Http\Controllers\EmployeeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Models\Employee; //add Employee Model

class EmployeeController extends Controller
{
    public function index(){
 		$employee = DB::table('employees')
 					->join('genders', 'genders.id', '=', 'employees.gender_id')
 					->join('positions', 'positions.id', '=', 'employees.position_id')
 					->get();
 
 		$gender = DB::table('genders')
 					->get();
 
 		$position = DB::table('positions')
 					->get();
 
    	return view('home', ['employees' => $employee , 'genders' => $gender , 'positions' => $position]);
    }
	
    public function save(Request $request){
    	$employee = new Employee;
    	$employee->firstname = $request->input('firstname');
    	$employee->lastname = $request->input('lastname');
    	$employee->gender_id = $request->input('gender');
    	$employee->position_id = $request->input('position');
 
  		$employee->save();
 
  		return redirect('/');
    }
}
Creating Model
php artisan make:model Employee -m
php artisan make:model Position -m
php artisan make:model Gender -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Employee -m

This will create our model file located : blog\app\Models\Employee.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_empoyees_table.php
edit code blog\database\migrations\create_empoyees_table.php
<?php
//blog\database\migrations\create_employees_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->integer('gender_id');
            $table->integer('position_id');
            $table->timestamps();
        });
    }
};

<?php
//blog\database\migrations\create_positions_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('positions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }
};

<?php
//blog\database\migrations\create_genders_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('genders', function (Blueprint $table) {
            $table->increments('id');
            $table->string('gender');
            $table->timestamps();
        });
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});
 
Route::get('/', 'EmployeeController@index');
 
Route::post('/save', 'EmployeeController@save');
Creating Views
blog\resources\views\home.blade.php
//blog\resources\views\home.blade.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Laravel 9 Joining Tables Insert Data in Bootstrap 5 Modal - Cairocoders</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Laravel 9 Joining Tables Insert Data in Bootstrap 5 Modal</h1>
	<div class="row">
		<div class="col-md-12">
			<h2>Employee Table
				<button type="button" class="btn btn-primary float-end" data-bs-toggle="modal" data-bs-target="#addnew">
				  <i class="bi bi-clipboard2-plus-fill"></i> Add New Employee
				</button>
			</h2>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Firsttname</th>
					<th>Lastname</th>
					<th>Gender</th>
					<th>Position</th>
				</thead>
				<tbody>
					@foreach($employees as $employee)
						<tr>
							<td>{{$employee->firstname}}</td>
							<td>{{$employee->lastname}}</td>
							<td>{{$employee->gender}}</td>
							<td>{{$employee->title}}</td>
						</tr>
					@endforeach
				</tbody>
			</table>
		</div>
	</div>
</div>
@include('modal')
</body>
</html>
blog\resources\views\modal.blade.php
//blog\resources\views\modal.blade.php
<!-- Add Modal -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
		<div class="modal-body">
			<form action="{{ URL::to('save') }}" method="POST">
				{{ csrf_field() }}
				<div class="mb-3 row">
					<label for="firstname" class="col-sm-2 col-form-label">Firstname</label>
					<div class="col-auto">
						<input type="text" name="firstname" class="form-control" placeholder="Input Firstname" required>
					</div>
				</div>
				<div class="mb-3 row">
					<label for="lastname" class="col-sm-2 col-form-label">Lastname</label>
					<div class="col-auto">
						<input type="text" name="lastname" class="form-control" placeholder="Input Lastname" required>
					</div>
				</div>
				<div class="mb-3 row">
					<label for="gender" class="col-sm-2 col-form-label">Gender</label>
					<div class="col-auto">
						<select class="form-select" name="gender">
							@foreach($genders as $gender)
								<option value="{{ $gender->id }}">{{ $gender->gender }}</option>
							@endforeach
						</select>
					</div>
				</div>
				<div class="mb-3 row">
					<label for="position" class="col-sm-2 col-form-label">Position</label>
					<div class="col-auto">
				    	<select class="form-select" name="position">
				    		@foreach($positions as $position)
				    			<option value="{{ $position->id }}">{{ $position->title }}</option>
				    		@endforeach
				    	</select>
					</div>
				</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="bi bi-x-circle-fill"></i> Close</button>
        <button type="submit" class="btn btn-primary"><i class="bi bi-send"></i> Save</button>
      </div>
    </div>
  </div>
</div>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Friday, April 22, 2022

Laravel 9 Search using AJAX

Laravel 9 Search using AJAX
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller MemberController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller MemberController
change it with the following codes:
blog\app\Http\Controllers\MemberController.php
//blog\app\Http\Controllers\MemberController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member; //add members Model

class MemberController extends Controller
{
    public function index(){
    	$members = Member::all();
    	return view('search')->with('members', $members);
    }
 
    public function search(Request $request){
    	$search = $request->input('search');
 
	    $members = Member::where('firstname', 'like', "$search%")
	       ->orWhere('lastname', 'like', "$search%")
	       ->get();
 
	    return view('result')->with('members', $members);
    }
 
    public function viewmember($id){
 
        $member = Member::find($id);
 
        return view('member')->with('member', $member);
    }
 
    public function find(Request $request){
        $search = $request->input('search');
 
        $members = Member::where('firstname', 'like', "$search%")
           ->orWhere('lastname', 'like', "$search%")
           ->get();
 
        return view('searchresult')->with('members', $members);
    }
}
Creating Model
php artisan make:model Member -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Member -m

This will create our model in the form of File.php file located : blog\app\Models\Member.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_members_table.php
edit code blog\database\migrations\create_members_table.php
<?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('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});

Route::get('/', 'MemberController@index');
Route::get('/search','MemberController@search');
Route::get('/member/{id}','MemberController@viewmember');
Route::post('/find','MemberController@find');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Search using AJAX - cairocoders</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:weight@100;200;300;400;500;600;700;800&display=swap");
body {
    background-color: #eee;
    font-family: "Poppins", sans-serif;
    font-weight: 300
}
.height {
    height: 100vh
}
.search {
    position: relative;
    box-shadow: 0 0 40px rgba(51, 51, 51, .1)
}
.search input {
    height: 60px;
    text-indent: 25px;
    border: 2px solid #d6d4d4
}
.search input:focus {
    box-shadow: none;
    border: 2px solid blue
}
.search button {
    position: absolute;
    top: 5px;
    right: 5px;
    height: 50px;
    width: 110px;
    background: blue
}
</style>
</head>
<body>
<div class="container">
    <div class="row justify-content-center align-items-center">
        <div class="col-md-8">
			<h2 class="page-header text-center">Laravel 9 Search using AJAX</h2>
            <div class="search"> <i class="fa fa-search"></i> 
			<form class="navbar-form navbar-left" action="{{ URL::to('find') }}" method="POST">
    		    {{ csrf_field() }}
    		        <input type="text" id="search" name="search" class="form-control" placeholder="Search Member" autocomplete="off">
					<button type="submit" class="btn btn-primary">Search</button> 
    		</form>
			</div>
            
			<div id="result" class="panel panel-default" style="display:none">
				<ul class="list-group" id="memList">
				
				</ul>
			</div>
		</div>
		
		@yield('content')
		
    </div>
</div>
<script type="text/javascript">
$(document).ready(function(){
    $.ajaxSetup({
    	headers: {
    		'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    	}
    });
     
    $('#search').keyup(function(){
    	var search = $('#search').val();
    	if(search==""){
    		$("#memList").html("");
    		$('#result').hide();
    	}
    	else{
    		$.get("{{ URL::to('search') }}",{search:search}, function(data){
    			$('#memList').empty().html(data);
    			$('#result').show();
    		})
    	}
    });
});
</script>
</body>
</html>
blog\resources\views\search.blade.php
//blog\resources\views\search.blade.php
    @extends('app')
     
    @section('content')
    	<div class="col-md-8">
    		<h4>Members Table</h4>
    		<table class="table table-bordered table-striped">
    			<thead>
    				<th>Firstname</th>
    				<th>Lastname</th>
    			</thead>
    			<tbody>
    				@foreach($members as $member)
    					<tr>
    						<td>{{$member->firstname}}</td>
    						<td>{{$member->lastname}}</td>
    					</tr>
    				@endforeach
    			</tbody>
    		</table>
    	</div>
    @endsection
blog\resources\views\result.blade.php
//blog\resources\views\result.blade.php
	@if(count($members) > 0)
    	@foreach($members as $member)
    		<li class="list-group-item"><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
    	@endforeach
    @else
    	<li class="list-group-item">No Results Found</li>
    @endif
blog\resources\views\search.blade.php
//blog\resources\views\search.blade.php
    @extends('app')
     
    @section('content')
    	<div class="col-md-8">
    		<h4>Members Table</h4>
    		<table class="table table-bordered table-striped">
    			<thead>
    				<th>Firstname</th>
    				<th>Lastname</th>
    			</thead>
    			<tbody>
    				@foreach($members as $member)
    					<tr>
    						<td>{{$member->firstname}}</td>
    						<td>{{$member->lastname}}</td>
    					</tr>
    				@endforeach
    			</tbody>
    		</table>
    	</div>
    @endsection
blog\resources\views\searchresult.blade.php
//blog\resources\views\searchresult.blade.php
    @extends('app')
     
    @section('content')
    	@if(count($members) > 0)
    		<h2>Search Results</h2>
    		<ul class="list-group">
    			@foreach($members as $member)
    				<li class="list-group-item"><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
    			@endforeach
    		</ul>
    	@else
    		<h2>No Results Found</h2>
    	@endif
    @endsection
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Thursday, April 21, 2022

SwiftUI Custom Badge Button

SwiftUI Custom Badge Button

ContentView.swift
 
//
//  ContentView.swift
//  CairocodersDev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State var count = 0
    @State var show = false
    
    var body: some View {
           
        GeometryReader { geometry in
            VStack {
                if self.show && self.count != 0 {
                    HStack(spacing: 12) {
                        
                        Image(systemName: "suit.heart.fill")
                            .resizable()
                            .frame(width: 20, height: 18)
                            .foregroundColor(.red)
                        
                        Text("\(self.count) Likes")
                    }
                    .padding([.horizontal,.top], 15)
                    .padding(.bottom, 30)
                    .background(Color.white)
                    .clipShape(ArrowShape())
                }
                
                Button(action: {
                    self.count += 1
                    self.show.toggle()
                }) {
                    Image(systemName: !self.show ? "suit.heart" : "suit.heart.fill")
                        .resizable()
                        .frame(width: 20, height: 18)
                        .foregroundColor(.red)
                        .padding()
                        .background(Color.white)
                        .clipShape(Circle())
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
        }
        .background(Color.black.opacity(0.06)).edgesIgnoringSafeArea(.all)
        .animation(.interactiveSpring(response: 0.6, dampingFraction: 1, blendDuration: 1))
        .onTapGesture {
            self.show.toggle()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ArrowShape : Shape {
    
    func path(in rect: CGRect) -> Path {
        return Path{path in
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: rect.width, y: 0))
            path.addLine(to: CGPoint(x: rect.width, y: rect.height - 10))
            
            path.addLine(to: CGPoint(x: (rect.width / 2) - 10, y: rect.height - 10))
            path.addLine(to: CGPoint(x: (rect.width / 2), y: rect.height))
            path.addLine(to: CGPoint(x: (rect.width / 2) + 10, y: rect.height - 10))
            
            path.addLine(to: CGPoint(x: 0, y: rect.height - 10))
        }
    }
}

Wednesday, April 20, 2022

Laravel 9 Datatables Server Side Data Processing

Laravel 9 Datatables Server Side Data Processing

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

jQuery DataTables API for Laravel
https://github.com/yajra/laravel-datatables

composer require yajra/laravel-datatables-oracle:"~9.0"
C:\xampp\htdocs\laravel9\blog>composer require yajra/laravel-datatables-oracle:"~9.0"

https://datatables.net/

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller ProductController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller ProductController
change it with the following codes:

blog\app\Http\Controllers\ProductController.php
//blog\app\Http\Controllers\ProductController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product; //add Product Model

class ProductController extends Controller
{
    public function getData(Request $request){
        if ($request->ajax()) {
             //$datas = Product::all();
             return datatables()->of(Product::all())->toJson();
         }        
         return view('products');
     }
}
Creating Model
php artisan make:model Product -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Product -m

This will create our model located : blog\app\Models\Product.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_products_table.php
edit code blog\database\migrations\create_products_table.php
//blog\database\migrations\create_products_table.php
<?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('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('price');
            $table->timestamps();
        });
    }

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

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
    
Route::get('table', 'ProductController@getData')->name('table');
Creating Views
blog\resources\views\products.blade.php
//blog\resources\views\products.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Datatables Server Side Data Processing - Cairocoders</title>
    <meta name="csrf-token" content="{{ csrf_token() }}"> 
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
    <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
    <h2>Laravel 9 Datatables Server Side Data Processing</h2>
    <table class="table table-bordered table-striped" id="data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Price</th>               
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<script type="text/javascript">
  $(function () {
    
    var table = $('#data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "table",
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'price', name: 'price'},         
        ]
    });
    
  });
</script>
</body>
</html>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Tuesday, April 19, 2022

Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event

Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event

Bootstrap 3
https://getbootstrap.com/docs/3.3/getting-started/

https://cdnjs.com/libraries/moment.js

The Most Popular JavaScript Calendar
https://fullcalendar.io/
https://cdnjs.com/libraries/fullcalendar/3.5.1

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller FullCalendarController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller FullCalendarController
change it with the following codes:
//blog\app\Http\Controllers\FullCalendarController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Event; //add Event Model

class FullCalendarController extends Controller
{
    public function getEvent(){
        if(request()->ajax()){
            $start = (!empty($_GET["start"])) ? ($_GET["start"]) : ('');
            $end = (!empty($_GET["end"])) ? ($_GET["end"]) : ('');
            $events = Event::whereDate('start', '>=', $start)->whereDate('end',   '<=', $end)
                    ->get(['id','title','start', 'end']);
            return response()->json($events);
        }
        return view('fullcalendar');
        
    }
    public function createEvent(Request $request){
        $data = $request->except('_token');
        $events = Event::insert($data);
        return response()->json($events);
    }
   
    public function deleteEvent(Request $request){
        $event = Event::find($request->id);
        return $event->delete();
    }
}
Creating Model
php artisan make:model Event -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Event -m

This will create our model in the form of File.php file located : blog\app\Models\Event.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_events_table.php
edit code blog\database\migrations\create_events_table.php
<?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('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->dateTime('start');
            $table->dateTime('end');
            $table->timestamps();
        });
    }

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

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table
//blog\app\Models\Event.php
<?php

namespace App\Models;

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

class Event extends Model
{
    use HasFactory;
    protected $fillable = ['title','start_date','end_date'];
}
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});
   
Route::get('/getevent', 'FullCalendarController@getEvent')->name('getevent');
Route::post('/createevent','FullCalendarController@createEvent')->name('createevent');
Route::post('/deleteevent','FullCalendarController@deleteEvent')->name('deleteevent');
Creating Views
blog\resources\views\fullcalendar.blade.php
//blog\resources\views\fullcalendar.blade.php
<!doctype html>
<html lang="en">
<head>
<title>Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event </title>
  <link href='https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css' rel='stylesheet'>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.5.1/fullcalendar.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.5.1/fullcalendar.min.js"></script>
</head>
<body>
<div class="container"><p><h1>Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event </h1></p>
    <div class="panel panel-primary">
        <div class="panel-heading">
               Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event 
        </div>
        <div class="panel-body" >
            <div id='calendar'></div>
        </div>
    </div>
</div>
</body>
<script>
    $(document).ready(function () {
        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            navLinks: true,
            editable: true,
            events: "getevent",           
            displayEventTime: false,
            eventRender: function (event, element, view) {
                if (event.allDay === 'true') {
                    event.allDay = true;
                } else {
                    event.allDay = false;
                }
            },
        selectable: true,
        selectHelper: true,
        select: function (start, end, allDay) {
            var title = prompt('Event Title:');
            if (title) {
                var start = moment(start, 'DD.MM.YYYY').format('YYYY-MM-DD'); 
                var end = moment(end, 'DD.MM.YYYY').format('YYYY-MM-DD'); 
                $.ajax({ 
                    url: "{{ URL::to('createevent') }}",
                    data: 'title=' + title + '&start=' + start + '&end=' + end +'&_token=' +"{{ csrf_token() }}",
                    type: "post",
                    success: function (data) {
                        alert("Added Successfully");
                        $('#calendar').fullCalendar('refetchEvents');
                    }
                });
            }
        },
        eventClick: function (event) {
            var deleteMsg = confirm("Do you really want to delete?");
            if (deleteMsg) { 
               $.ajax({
                    type: "POST",
                    url: "{{ URL::to('deleteevent') }}",
                    data: "&id=" + event.id+'&_token=' +"{{ csrf_token() }}",
                    success: function (response) {
                        if(parseInt(response) > 0) {
                            $('#calendar').fullCalendar('removeEvents', event.id);
                            alert("Deleted Successfully");
                        }
                    }
                });
            }
        }
        });
    });
</script>
</html>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Monday, April 18, 2022

Laravel 9 Multiple File Upload | File Storage

Laravel 9 Multiple File Upload | File Storage

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller UploadController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller UploadController
change it with the following codes:
blog\app\Http\Controllers\UploadController.php
//blog\app\Http\Controllers\UploadController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File; //add File Model

class UploadController extends Controller
{
    public function index(){
 
    	$files = File::all();
    	return view('upload')->with('files', $files);
    }
 
    public function store(Request $request){
 
    	$messages = [
    		'required' => 'Please select file to upload',
		];
 
    	$this->validate($request, [
    		'file' => 'required',
    	], $messages);
 
    	foreach ($request->file as $file) {
    		$filename = time().'_'.$file->getClientOriginalName();
	    	$filesize = $file->getSize();
	    	$file->storeAs('public/',$filename);
	    	$fileModel = new File;
	    	$fileModel->name = $filename;
	    	$fileModel->size = $filesize;
	    	$fileModel->location = 'storage/'.$filename;
	    	$fileModel->save();    		
    	}
 
    	return redirect('/')->with('success', 'File/s Uploaded Successfully');
 
    }
}
Creating Model
php artisan make:model File -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model File -m

This will create our model in the form of File.php file located : blog\app\Models\File.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_members_table.php
edit code blog\database\migrations\create_file_table.php
<?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('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('size');
            $table->string('location');
            $table->timestamps();
        });
    }

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

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});
  
Route::get('/','UploadController@index');
Route::post('/store','UploadController@store')->name('upload.file');
Creating Views
blog\resources\views\upload.blade.php
//blog\resources\views\upload.blade.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Laravel File Upload</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Laravel 9 Multiple File Upload | File Storage</h1>
	<div class="row">
		<div class="col-4">
			<div class="card">
				<div class="card-header">Upload Form</div>
				<div class="card-body">
					<form method="POST" action="{{ route('upload.file') }}" enctype="multipart/form-data">
						{{ csrf_field() }}
						<input type="file" name="file[]" multiple><br><br>
						<button type="submit" class="btn btn-primary">Upload</button>
					</form>
				</div>
			</div>
			<div style="margin-top:20px;">
			@if(count($errors) > 0)
				@foreach($errors->all() as $error)
					<div class="alert alert-danger text-center">
						{{$error}}
					</div>
				@endforeach
			@endif
 
			@if(session('success'))
				<div class="alert alert-success text-center">
					{{session('success')}}
				</div>
			@endif
			</div>
		</div>
		<div class="col-8">
			<h2>Files Table</h2>
				<table class="table table-bordered table-striped">
					<thead>
						<th>Photo</th>
						<th>File Name</th>
						<th>File Size</th>
						<th>Date Uploaded</th>
						<th>File Location</th>
					</thead>
					<tbody>
						@if(count($files) > 0)
							@foreach($files as $file)
								<tr>
									<td><img src='storage/{{$file->name}}' name="{{$file->name}}" style="width:90px;height:90px;"></td>
									<td>{{ $file->name }}</td>
									<td> 
										@if($file->size < 1000)
											{{ number_format($file->size,2) }} bytes
										@elseif($file->size >= 1000000)
											{{ number_format($file->size/1000000,2) }} mb
										@else
											{{ number_format($file->size/1000,2) }} kb
										@endif
									</td>
									<td>{{ date('M d, Y h:i A', strtotime($file->created_at)) }}</td>
									<td><a href="{{ $file->location }}">{{ $file->location }}</a></td>

								</tr>
							@endforeach
						@else
							<tr>
								<td colspan="5" class="text-center">No Table Data</td>
							</tr>
						@endif
					</tbody>
				</table>
		</div>
	</div>
</div>
</body>
</html>
File Storage https://laravel.com/docs/9.x/filesystem
php artisan storage:link
C:\xampp\htdocs\laravel9\blog>php artisan storage:link
The [C:\xampp\htdocs\laravel9\blog\public\storage] link has been connected to [C:\xampp\htdocs\laravel9\blog\storage\app/public].
The links have been created.

Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Friday, April 15, 2022

Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper

Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Croppie
Croppie is a fast, easy to use image cropping plugin with tons of configuration options!

https://foliotek.github.io/Croppie/
https://cdnjs.com/libraries/croppie
https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css
index.php
//index.php
<html>  
  <head>  
    <title>Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper</title>  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
	
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
	<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
  </head>  
<body>  
<div class="container" style="margin-top:20px;padding:20px;">  
	<div class="card">
	  <div class="card-header">
		Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper
	  </div>
	  <div class="card-body">
		<h5 class="card-title">Select Image</h5>
		<input type="file" name="upload_image" id="upload_image" />       
	  </div>
	</div>

	<div class="card text-center" id="uploadimage" style='display:none'>
	  <div class="card-header">
		Upload & Crop Image
	  </div>
	  <div class="card-body">
		    <div id="image_demo" style="width:350px; margin-top:30px"></div>
            <div id="uploaded_image" style="width:350px; margin-top:30px;"></div>  
	  </div>
	  <div class="card-footer text-muted">
		<button class="crop_image">Crop & Upload Image</button>
	  </div>
	</div>
</div>
</body>  
</html>
 
<script>  
$(document).ready(function(){
 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'circle' //circle
    },
    boundary:{
      width:300,
      height:300
    }
  });
  $('#upload_image').on('change', function(){
    var reader = new FileReader();
    reader.onload = function (event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }) 
    }
    reader.readAsDataURL(this.files[0]);
    $('#uploadimage').show();
  });
  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"image": response},
        success:function(data)
        {
           $('#uploaded_image').html(data)
        }
      });
    })
  });
});  
</script>
upload.php
//upload.php
<?php
if(isset($_POST["image"]))
{
 $data = $_POST["image"];
 $image_array_1 = explode(";", $data);
 $image_array_2 = explode(",", $image_array_1[1]);
 $data = base64_decode($image_array_2[1]);
 $imageName = time() . '.png';
 file_put_contents($imageName, $data);
 echo '<img src="'.$imageName.'" class="img-thumbnail" />';
}
?>

Thursday, April 14, 2022

Laravel 9 CRUD (Create, Read, Update and Delete) - Bootstrap 5 Modal Add Edit and Delete

Laravel 9 CRUD (Create, Read, Update and Delete) - Bootstrap 5 Modal Add Edit and Delete

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller MemberController 
C:\xampp\htdocs\laravel9\blog>php artisan make:controller MemberController

controller created file located at :  youproject/app/Http/Controller
blog\app\Http\Controllers\MemberController.php

change it with the following codes:

blog\app\Http\Controllers\MemberController.php
blog\app\Http\Controllers\MemberController.php
//blog\app\Http\Controllers\MemberController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member; //add Member Models

class MemberController extends Controller
{
    public function index(){
    	return view('show');
    }

    public function getMembers(){
    	$members = Member::all();

    	return view('show')->with('members', $members);
    }

    public function save(Request $request){
    	$member = new Member;
    	$member->firstname = $request->input('firstname');
    	$member->lastname = $request->input('lastname');
  		$member->save();

  		return redirect('/');
    }

    public function update(Request $request, $id){
    	$member = Member::find($id);
    	$input = $request->all();
		$member->fill($input)->save();

    	return redirect('/');
    }

    public function delete($id)
    {
        $members = Member::find($id);
        $members->delete();
 
        return redirect('/');
    }
}
Create Model

php artisan make:model Member -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Member -m

This will create our model in the form of Member.php file located : blog\app\Models\Member.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_members_table.php
edit code blog\database\migrations\create_members_table.php
//blog\database\migrations\create_members_table.php
increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->timestamps();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
}
Database Migration

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table created table created member
blog\app\Models\Member.php
//blog\app\Models\Member.php
<?php

namespace App\Models;

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

class Member extends Model
{
    use HasFactory;
	protected $fillable  = ['firstname', 'lastname'];
}
Creating Routes
blog\routes\web.php
////blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});
 
Route::get('/', 'MemberController@index');

Route::get('/', 'MemberController@getMembers');

Route::post('/save', 'MemberController@save');

Route::patch('/update/{id}', ['as' => 'member.update', 'uses' => 'MemberController@update']);

Route::delete('/delete/{id}', ['as' => 'member.delete', 'uses' => 'MemberController@delete']);
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Laravel 9 Crud - Bootstrap 5 Modal Add Edit and Delete</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
	@yield('content')
</div>
@include('modal')

</body>
</html>
blog\resources\views\show.blade.php
//blog\resources\views\show.blade.php
@extends('app')

@section('content')
<h1 class="page-header text-center">Laravel 9 CRUD (Create, Read, Update and Delete) - Bootstrap 5 Modal Add Edit and Delete</h1>
<div class="row">
	<div class="col-md-12 col-md-offset-1">
		<h2>Members Table
			<button type="button" data-bs-toggle="modal" data-bs-target="#addnew" class="btn btn-primary pull-right"><i class="fa fa-plus"></i> Member</button>
		</h2>
	</div>
</div>
<div class="row">
	<div class="col-md-12 col-md-offset-1">
		<table class="table table-bordered table-responsive table-striped">
			<thead>
				<th>Fisrtname</th>
				<th>Lastname</th>
				<th>Action</th>
			</thead>
			<tbody>
				@foreach($members as $member)
					<tr>
						<td>{{$member->firstname}}</td>
						<td>{{$member->lastname}}</td>
						<td>
							<a href="#edit{{$member->id}}" data-bs-toggle="modal" class="btn btn-success"><i class='fa fa-edit'></i> Edit</a> 
							<a href="#delete{{$member->id}}" data-bs-toggle="modal" class="btn btn-danger"><i class='fa fa-trash'></i> Delete</a>
							@include('action')
						</td>
					</tr>
				@endforeach
			</tbody>
		</table>
	</div>
</div>
@endsection
blog\resources\views\modal.blade.php
//blog\resources\views\modal.blade.php
<!-- Add Modal -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="addnewModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
		<div class="modal-header">
			<h5 class="modal-title" id="addnewModalLabel">Add New Member</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		</div>
		<div class="modal-body">
				{!! Form::open(['url' => 'save']) !!}
			    	<div class="mb-3">
				    	{!! Form::label('firstname', 'Firstname') !!}
				    	{!! Form::text('firstname', '', ['class' => 'form-control', 'placeholder' => 'Input Firstname', 'required']) !!}
			    	</div>
			    	<div class="mb-3">
				    	{!! Form::label('lastname', 'Lastname') !!}
				    	{!! Form::text('lastname', '', ['class' => 'form-control', 'placeholder' => 'Input Lastname', 'required']) !!}
			    	</div>
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
			<button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>
			{!! Form::close() !!}
		</div>
    </div>
  </div>
</div>
Class "Collective\Html\HtmlServiceProvider" not found

composer require laravelcollective/html --prefer-source
C:\xampp\htdocs\laravel9\blog>composer require laravelcollective/html --prefer-source
blog\resources\views\action.blade.php
//blog\resources\views\action.blade.php
<!-- Edit Modal -->
<div class="modal fade" id="edit{{$member->id}}" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
		<div class="modal-header">
			<h5 class="modal-title" id="myModalLabel">Edit Member</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		</div>
		<div class="modal-body">
				{!! Form::model($members, [ 'method' => 'patch','route' => ['member.update', $member->id] ]) !!}
			    	<div class="mb-3">
				    	{!! Form::label('firstname', 'Firstname') !!}
						{!! Form::text('firstname', $member->firstname, ['class' => 'form-control']) !!}
			    	</div>
			    	<div class="mb-3">
				    	{!! Form::label('lastname', 'Lastname') !!}
				    	{!! Form::text('lastname', $member->lastname, ['class' => 'form-control']) !!}
			    	</div>
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
			{{Form::button('<i class="fa fa-check-square-o"></i> Update', ['class' => 'btn btn-success', 'type' => 'submit'])}}
			{!! Form::close() !!}
		</div>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="delete{{$member->id}}" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
		<div class="modal-header">
			<h5 class="modal-title" id="myModalLabel">Delete Member</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		</div>
		<div class="modal-body">
			{!! Form::model($members, [ 'method' => 'delete','route' => ['member.delete', $member->id] ]) !!}
				<h4 class="text-center">Are you sure you want to delete Member?</h4>
				<h5 class="text-center">Name: {{$member->firstname}} {{$member->lastname}}</h5>
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
			{{Form::button('<i class="fa fa-trash"></i> Delete', ['class' => 'btn btn-danger', 'type' => 'submit'])}}
			{!! Form::close() !!}
		</div>
    </div>
  </div>
</div>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Wednesday, April 13, 2022

Python Django Ajax Insert Data and Validate Nick Name

Python Django Ajax Insert Data and Validate Nick Name

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp.views import (
    indexView,
    postEmployee, 
    checkNickName
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', indexView),
    path('post/ajax/employee', postEmployee, name = "post_employee"),
    path('get/ajax/validate/nickname', checkNickName, name = "validate_nickname"),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.core import serializers
from .forms import EmployeeForm
from .models import Employee

def indexView(request):
    form = EmployeeForm()
    empoyees = Employee.objects.all()
    return render(request, "index.html", {"form": form, "empoyees": empoyees})

def postEmployee(request):
    if request.is_ajax and request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            instance = form.save()
            ser_instance = serializers.serialize('json', [ instance, ])
            return JsonResponse({"instance": ser_instance}, status=200)
        else:
            return JsonResponse({"error": form.errors}, status=400)

    return JsonResponse({"error": ""}, status=400)

def checkNickName(request):
    if request.is_ajax and request.method == "GET":
        nick_name = request.GET.get("nick_name", None)
        if Employee.objects.filter(nick_name = nick_name).exists():
            return JsonResponse({"valid":False}, status = 200)
        else:
            return JsonResponse({"valid":True}, status = 200)

    return JsonResponse({}, status = 400)
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Employee(models.Model):
    # NICK NAME should be unique
    nick_name = models.CharField(max_length=100, unique =  True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    dob = models.DateField(auto_now=False, auto_now_add=False)
    lives_in = models.CharField(max_length=150, null = True, blank = True)

    def __str__(self):
        return self.nick_name
myapp/forms.py
 
//myapp/forms.py
from .models import Employee
from django import forms
import datetime

class EmployeeForm(forms.ModelForm):
    ## change the widget of the date field.
    dob = forms.DateField(
        label='What is your birth date?', 
        # change the range of the years from 1980 to currentYear - 5
        widget=forms.SelectDateWidget(years=range(1980, datetime.date.today().year-5))
    )
    
    def __init__(self, *args, **kwargs):
        super(EmployeeForm, self).__init__(*args, **kwargs)
        ## add a "form-control" class to each form input bootstrap
        for name in self.fields.keys():
            self.fields[name].widget.attrs.update({
                'class': 'form-control',
            })

    class Meta:
        model = Employee
        fields = ("__all__")
myapp/templates/index.html
 
//myapp/templates/index.html	
{% extends 'base.html' %}

{% block body %}
<div class="container-fluid">
  <form id="employee-form">
        <div class="row">
            {% csrf_token %}
            {% for field in form %}
            <div class="form-group col-4">
                <label class="col-12">{{ field.label }}</label>
                {{ field }}
            </div>
            {% endfor %}
        </div>
        <div class="row" style="margin:20px;">
            <input type="submit" class="btn btn-primary" value="Create Employee" style="width:300px;"/>
        </div>
  <form>
</div>

<hr />

<div class="container-fluid">
    <table class="table table-striped table-sm" id="my_employee">
        <thead>
            <tr>
                <th>Nick name</th>
                <th>First name</th>
                <th>Last name</th>
                <th>DOB</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
        {% for rs in empoyees %}
        <tr>
            <td>{{rs.nick_name}}</td>
            <td>{{rs.first_name}}</td>
            <td>{{rs.last_name}}</td>
            <td>{{rs.dob | date:"Y-m-d"}}</td>
            <td>{{rs.lives_in}}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>

</div>
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Django Ajax Insert Data and Validate Nick Name</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
    <div class="container">
        <div class="row">
            <p><h3 class="text-primary">Python Django Ajax Insert Data and Validate Nick Name</h3></p>
            <hr style="border-top:1px dotted #ccc;"/>
            {% block body %}
      
            {% endblock %}
        </div>
    </div> 
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {

            $("#employee-form").submit(function (e) {
                e.preventDefault();
                var serializedData = $(this).serialize();
                $.ajax({
                    type: 'POST',
                    url: "{% url 'post_employee' %}",
                    data: serializedData,
                    success: function (response) {
                        $("#employee-form").trigger('reset'); // clear the form.
                        $("#id_nick_name").focus(); // focus to nickname input 
    
                        var instance = JSON.parse(response["instance"]);
                        var fields = instance[0]["fields"];
                        $("#my_employee tbody").prepend(
                            `<tr>
                            <td>${fields["nick_name"]||""}</td>
                            <td>${fields["first_name"]||""}</td>
                            <td>${fields["last_name"]||""}</td>
                            <td>${fields["dob"]||""}</td>
                            <td>${fields["lives_in"]||""}</td>
                            </tr>`
                        )
                    },
                    error: function (response) {
                        alert(response["responseJSON"]["error"]); // alert the error if any error occured
                    }
                })
            })
    
            $("#id_nick_name").focusout(function (e) {
                e.preventDefault();
                var nick_name = $(this).val();
                $.ajax({
                    type: 'GET',
                    url: "{% url 'validate_nickname' %}",
                    data: {"nick_name": nick_name},
                    success: function (response) {
                        if(!response["valid"]){ // if not valid user, alert the user
                            alert("You cannot create a Employee with same nick name");
                            var nickName = $("#id_nick_name");
                            nickName.val("")
                            nickName.focus()
                        }
                    },
                    error: function (response) {
                        console.log(response)
                    }
                })
            })
})
</script>
</body>
</html>
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
migration
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate

SwiftUI how to implement infinite scrolling with view details

SwiftUI how to implement infinite scrolling with view details

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
 
struct ContentView: View {
    
    @ObservedObject var sc = SourceCountry()
    @State var nextIndex = 1
    
    init() {
        sc.getCountry(at: 0)
    }
    
    @State var show = false
    
    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack(alignment: .leading) {
                    ForEach(sc.countries.indices, id: \.self) { countryIndex in
                        let country = sc.countries[countryIndex]
                        
                        NavigationLink(destination: DetailsView(viewdata: Country(id: country.id, emoji: country.emoji, name: country.name))) {
                            
                            VStack {
                                Text(country.name)
                                    .font(.title)
                                    .fontWeight(.bold)
                                
                                Text("\(country.emoji)")
                                    .font(.system(size: 200))
                                    .padding(.horizontal)
                                    .onAppear {
                                        if countryIndex == sc.countries.count - 3 {
                                            sc.getCountry(at: nextIndex)
                                            nextIndex += 1
                                        }
                                    }
                            }
                        }
                    }
                }
                .padding()
            }
            .navigationTitle("Country")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Model.swift
 
//
//  Model.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct Country: Identifiable {
    let id: Int
    let emoji: String
    let name: String
}

class SourceCountry: ObservableObject {
    
    @Published var countries = [Country]()
    
    func getCountry(at index: Int) {
        
        print("page", index)
        
        switch index {
        case 0:
            countries.append(contentsOf: [
                Country(id: 1, emoji: "🇦🇩", name: "AD"),
                Country(id: 2, emoji: "🇦🇪", name: "AE"),
                Country(id: 3, emoji: "🇦🇫", name: "AF"),
                Country(id: 4, emoji: "🇦🇬", name: "AG"),
                Country(id: 5, emoji: "🇦🇮", name: "AI"),
                Country(id: 6, emoji: "🇦🇱", name: "AL"),
                Country(id: 7, emoji: "🇦🇲", name: "AM"),
                Country(id: 8, emoji: "🇦🇴", name: "AO"),
                Country(id: 9, emoji: "🇦🇶", name: "AQ"),
                Country(id: 10, emoji: "🇦🇷", name: "AR")
            ])
            
        case 1:
            countries.append(contentsOf: [
                Country(id: 11, emoji: "🇦🇸", name: "AS"),
                Country(id: 12, emoji: "🇦🇹", name: "AT"),
                Country(id: 13, emoji: "🇦🇺", name: "AU"),
                Country(id: 14, emoji: "🇦🇼", name: "AW"),
                Country(id: 15, emoji: "🇦🇽", name: "AX"),
                Country(id: 16, emoji: "🇦🇿", name: "AZ"),
                Country(id: 17, emoji: "🇧🇦", name: "BA"),
                Country(id: 18, emoji: "🇧🇧", name: "BB"),
                Country(id: 19, emoji: "🇧🇩", name: "BD"),
                Country(id: 20, emoji: "🇧🇪", name: "BE")
            ])
            

            
        case 2:
            countries.append(contentsOf: [
                Country(id: 21, emoji: "🇧🇫", name: "BF"),
                Country(id: 22, emoji: "🇧🇬", name: "BG"),
                Country(id: 23, emoji: "🇧🇭", name: "BH"),
                Country(id: 24, emoji: "🇧🇮", name: "BI"),
                Country(id: 25, emoji: "🇧🇯", name: "BJ"),
                Country(id: 26, emoji: "🇧🇱", name: "BL"),
                Country(id: 27, emoji: "🇧🇲", name: "BM"),
                Country(id: 28, emoji: "🇧🇳", name: "BN"),
                Country(id: 29, emoji: "🇧🇴", name: "BO"),
                Country(id: 30, emoji: "🇧🇶", name: "BQ")
            ])
            
        case 3:
            countries.append(contentsOf: [
                Country(id: 31, emoji: "🇧🇷", name: "BR"),
                Country(id: 32, emoji: "🇧🇸", name: "BS"),
                Country(id: 33, emoji: "🇧🇹", name: "BT"),
                Country(id: 34, emoji: "🇧🇻", name: "BV"),
                Country(id: 35, emoji: "🇧🇼", name: "BW"),
                Country(id: 36, emoji: "🇧🇾", name: "BY"),
                Country(id: 37, emoji: "🇧🇿", name: "BZ"),
                Country(id: 38, emoji: "🇨🇦", name: "CA"),
                Country(id: 39, emoji: "🇨🇨", name: "CC"),
                Country(id: 40, emoji: "🇨🇩", name: "CD")
            ])
            
        default:
            break
        }
    }
}
DetailsView.swift
 
//
//  DetailsView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailsView: View {
    
    var viewdata: Country
    
    var body: some View {
        VStack {
            Text("\(viewdata.emoji) \(viewdata.name)")
                .font(.system(size: 200))
                .padding(.horizontal)
        }
    }
}

struct DetailsView_Previews: PreviewProvider {
    static var previews: some View {
        DetailsView(viewdata: Country(id: 1, emoji: "🇦🇩", name: "Ph"))
    }
}

Tuesday, April 12, 2022

SwiftUI Clone Instagram Home Page

SwiftUI Clone Instagram Home Page

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
 
struct ContentView: View {

    var body: some View {
        VStack {
            TitleView()
            ScrollView {
                VStack {
                    StoryView()
                    Divider()
                    Spacer()
                    
                    ForEach(userpost) { post in
                        PostView(viewpost: post)
                    }
                }
                .navigationBarHidden(true)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
TitleView.swift
 
//
//  TitleView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct TitleView: View {
    var body: some View {
        HStack {
            Text("Instagram").font(.title)
            Spacer() // spacer to push buttons to right
            HStack(spacing: 16) { // right buttons
                Button (action: {
                   
                }) {
                    Image(systemName: "plus")
                        .resizable()
                        .frame(width: 10, height: 10)
                        .padding(4)
                }
                .overlay(RoundedRectangle(cornerSize: CGSize(width: 4, height: 4)).stroke(Color.black))
                Button (action: {
                }) {
                    Image(systemName: "heart")
                        .resizable()
                        .frame(width: 20, height: 20)
                }
                Button (action: {
                }) {
                    Image(systemName: "message")
                        .resizable()
                        .frame(width: 20, height: 20)
                }
            }
            .foregroundColor(.black) // make sure all button tint is black
        }
        .padding(EdgeInsets(top: 12, leading: 12, bottom: 4, trailing: 12))
    }
}

struct TitleView_Previews: PreviewProvider {
    static var previews: some View {
        TitleView()
    }
}
StoryView.swift
 
//
//  StoryView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct StoryView: View {
    
    @State var user: Userlist?
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            LazyHStack(alignment: .top, spacing: 0) {
                ForEach(users) { rs in
                    StoryItemView(viewdata: rs)
                        .padding(4)
                }
            }
        }
        .padding(.leading, 10)
        .listRowInsets(EdgeInsets())
    }
}

struct StoryItemView: View {
    
    @State var viewdata: Userlist
    
    var body: some View {
        VStack(spacing: 8) {
            Image(viewdata.photo) // image with red border
                .resizable()
                .frame(width: 64, height: 64, alignment: .center)
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.red, lineWidth: 2))
            Text(viewdata.username)
                .font(.caption)
                .lineLimit(1)
        }
        .frame(width: 72) // fixed size
    }
}

struct StoryView_Previews: PreviewProvider {
    static var previews: some View {
        StoryView()
    }
}
PostView.swift
 
//
//  PostView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct PostView: View {
    
    @State var viewpost: UserPost
    
    @State private var comment: String = ""
    var body: some View {
        VStack (alignment: .leading) {
            // User profile
            HStack {
                Image(viewpost.photo)
                    .resizable()
                    .frame(width: 40, height: 40)
                    .clipShape(Circle())
                VStack(alignment: .leading, spacing: 4) {
                    Text(viewpost.username).font(.subheadline).bold()
                    Text(viewpost.place)
                        .font(.caption)
                        .opacity(0.8)
                }
                Spacer()
                Button(action: {
                    
                }) {
                    Text("...").bold()
                }
                .foregroundColor(.black)
            }
            .padding(.leading, 12)
            .padding(.trailing, 12)
            // image
            Image(viewpost.postimage)
                .resizable()
                .scaledToFill()
                .frame(height: 280)
                .frame(maxWidth: .infinity)
                .clipped()
            // buttons
            HStack (spacing: 16) {
                Button (action: {
                    // add action here
                }) {
                    Image(systemName: "heart")
                        .resizable()
                        .frame(width: 18, height: 18)
                }
                Button (action: {
                    // add action here
                }) {
                    Image(systemName: "message")
                        .resizable()
                        .frame(width: 18, height: 18)
                }
                Button (action: {
                    // add action here
                }) {
                    Image(systemName: "location")
                        .resizable()
                        .frame(width: 18, height: 18)
                }
                Spacer()
                Button (action: {
                    // add action here
                }) {
                    Image(systemName: "bookmark")
                        .resizable()
                        .frame(width: 18, height: 18)
                }
            }
            .foregroundColor(.black)
            .padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
            // Text
            VStack (alignment: .leading, spacing: 4) {
                Text("5.3K likes").font(.caption).bold()
                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et").font(.caption)
                // profile image and comment textfield
                HStack {
                    Image("4")
                        .resizable()
                        .frame(width: 30, height: 30)
                        .clipShape(Circle())
                    TextField("Add a comment...", text: $comment).font(.subheadline)
                }
                // datetime
                Text("2 hours ago")
                    .font(.caption)
                    .foregroundColor(.gray)
            }
            .padding(.leading, 16)
            .padding(.trailing, 16)
        }
        .padding(.bottom, 24)
    }
}

struct PostView_Previews: PreviewProvider {
    static var previews: some View {
        PostView(viewpost: UserPost(id: 1, username: "cairocoders", place: "olongapo", description: "sample description", photo: "1", postimage: "post1"))
    }
}
Model.swift
 
//
//  Model.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct Userlist: Identifiable {
 
    let id: Int
    let username: String
    let photo : String
}
 
var users = [
    Userlist(id: 0, username: "Olivia", photo: "1"),
    Userlist(id: 1, username: "Emma", photo: "2"),
    Userlist(id: 2, username: "Ava", photo: "3"),
    Userlist(id: 3, username: "Charlotte", photo: "4"),
    Userlist(id: 4, username: "Sophia", photo: "5"),
    Userlist(id: 5, username: "Amelia", photo: "6")
]

struct UserPost: Identifiable {
 
    let id: Int
    let username: String
    let place: String
    let photo : String
    let postimage : String
}

var userpost = [
    UserPost(id: 0, username: "Olivia", place: "Olongapo City", photo: "1", postimage: "post1"),
    UserPost(id: 1, username: "Emma", place: "Angeles City", photo: "2", postimage: "post2"),
    UserPost(id: 2, username: "Ava", place: "San Fernando", photo: "3", postimage: "post3"),
    UserPost(id: 3, username: "Charlotte", place: "Manila", photo: "4", postimage: "post4"),
    UserPost(id: 4, username: "Sophia", place: "Pasay", photo: "5", postimage: "post5"),
    UserPost(id: 5, username: "Amelia", place: "Baliwag", photo: "6", postimage: "post6")
]

Related Post