Country and State table with Insert Operation in Database in Laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CountryController extends Controller
{
public function index()
{
$country = DB::table("country")->get();
return view("country", ["data" => $country]);
}
public function showCountry()
{
$country = DB::table("country")->get();
return view("countryHome", ["data" => $country]);
}
public function validateCountry(Request $request)
{
if ($request->validate([
"countryName" => "required",
"countryCode" => "required|unique:country,country_code",
"countryDial" => "required|numeric|unique:country,country_dial"
])) {
$country = Country::insert([
"country_name" => $request->countryName,
"country_code" => $request->countryCode,
"country_dial" => $request->countryDial,
"created_at" => now(), //now() is a helper function in laravel
"updated_at" => now()
]);
if ($country) {
$country = DB::table("country")->get();
return view("countryHome", ["data" => $country]);
}
return redirect()->route("showCountry.country");
} else {
return redirect()->route("country");
}
}
}
Above File is app\Http\Controllers\CountryController.php FileBelow File is app\Http\Controllers\StatesController.php File
<?php
namespace App\Http\Controllers;
use App\Models\States;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class StatesController extends Controller
{
public function index(Request $request)
{
$country = DB::table("country")->get();
return view("states", ["data" => $country]);
}
public function showStates()
{
$states = DB::table("states")->get();
return view("statesHome", ["data" => $states]);
}
public function validateStates(Request $request)
{
if ($request->validate([
"country" => "required",
"state" => [
'required',
'string',
'max:255',
// Ensure the combination of state name and country_id is unique
Rule::unique('states', 'state_name')->where(function ($query) use ($request) {
return $query->where('country_ID', $request->country);
}),
],
"status" => "required"
], [
'state.unique' => 'The state name already exists for the selected country.',
])) {
$states = States::insert([
"country_ID" => $request->country,
"state_name" => $request->state,
"status" => $request->status,
"created_at" => now(),
"updated_at" => now()
]);
if ($states) {
$states = DB::table("states")->get();
return view("statesHome", ["data" => $states]);
}
return redirect()->route("showStates.states");
} else {
return redirect()->route("states");
}
}
}
Below File is app\Models\Country.php File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
use HasFactory;
protected $table = "country";
protected $primarykey = "id";
protected $fillable = [
"country_name",
"country_code",
"country_dial_code"
];
}
Below File is app\Models\States.php File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class States extends Model
{
use HasFactory;
protected $table = "states";
protected $primarykey = "id";
protected $foreignkey = "country_ID";
protected $fillable = [
"country_ID",
"state_name",
"status"
];
}
Below File is database\migrations\2024_11_25_050822_create_country_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.
*/
public function up(): void
{
Schema::create('country', function (Blueprint $table) {
$table->id();
$table->string("country_name", 50);
$table->string("country_code");
$table->string("country_dial");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('country');
}
};
Below File is database\migrations\2024_11_25_053636_create_states_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.
*/
public function up(): void
{
// Here below, we have used "cascade" that means if we change anything in primary key table then it will automatically update in Foreign key table
Schema::create('states', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger("country_ID");
$table->foreign("country_ID")->references("id")->on("country")->onUpdate("cascade")->onDelete("cascade")->onDelete("set null");
$table->string("state_name", 50);
$table->boolean("status");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('states');
}
};
Below File is resources\views\country.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Country</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-4 card">
<div class="card-header">
<h1 class="mb-5 card-title">Add Country Details</h1>
</div>
<div class="card-body">
<form action="{{ route("validateCountry.country") }}" method="POST">
@csrf
<div class="mb-3">
<label for="exampleInputCountryName" class="form-label">Country Name</label>
<input type="text" class="form-control @error("countryName") is-invalid @enderror" id="exampleInputCountryName" aria-describedby="countryHelp" name="countryName">
@if($errors->has("countryName"))
<div class="error">{{ $errors->first("countryName") }}</div>
@endif
</div>
<div class="mb-3">
<label for="exampleInputCountryCode" class="form-label">Country ISO Code</label>
<input type="text" class="form-control @error("countryCode") is-invalid @enderror" id="exampleInputCountryCode" name="countryCode">
@if($errors->has("countryCode"))
<div class="error">{{ $errors->first("countryCode") }}</div>
@endif
</div>
<div class="mb-3">
<label for="exampleInputCountryDial" class="form-label">Country Dial</label>
<input type="text" class="form-control @error("countryDial") is-invalid @enderror" id="exampleInputCountryDial" name="countryDial">
@if($errors->has("countryDial"))
<div class="error">{{ $errors->first("countryDial") }}</div>
@endif
</div>
<button class="btn btn-primary mt-3">Submit</button>
<a href="{{ route("showCountry.country") }}" class="btn btn-primary mt-3">Go to Home</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Below File is resources\views\countryHome.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Home Screen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-10">
<a href="{{ route("country") }}" class="btn btn-primary mt-5 mb-5">Add New Country</a>
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Country Name</th>
<th>Country Code</th>
<th>Country Dial</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>
@foreach($data as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->country_name }}</td>
<td>{{ $value->country_code }}</td>
<td>{{ $value->country_dial }}</td>
<td>{{ $value->created_at }}</td>
<td>{{ $value->updated_at }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Below File is resources\views\states.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>States</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-4 card">
<div class="card-header">
<h1 class="mb-5 card-title">Add State Details</h1>
</div>
<div class="card-body">
<form action="{{ route("validateStates.states") }}" method="POST">
@csrf
<div class="mb-3">
<label for="exampleInputStateName" class="form-label">Enter State : </label>
<input type="text" class="form-control @error("state") is-invalid @enderror" id="exampleInputStateName" aria-describedby="countryHelp" name="state">
@if($errors->has("state"))
<div class="error">{{ $errors->first("state") }}</div>
@endif
</div><br>
<div class="mb-3">
<label for="state">Choose Country name : </label>
<select name="country" id="country" name="country">
@foreach($data as $key => $value)
<option value={{ $value->id }}>{{ $value->country_name }}</option>
@endforeach
</select>
@if($errors->has("country"))
<div class="error">{{ $errors->first("country") }}</div>
@endif
</div><br>
<p>Please select status : </p>
<input type="radio" id="active" name="status" value="1">
<label for="active">Active</label><br><br>
<input type="radio" id="inactive" name="status" value="0">
<label for="inactive">Inactive</label><br>
@if($errors->has("status"))
<div class="error">{{ $errors->first("status") }}</div>
@endif
<br><br>
<button type="submit" class="btn btn-primary">Submit</button>
<a href="{{ route("showStates.states") }}" class="btn btn-primary">Go to Home</a>
</form>
</div>
</div>
</div>
</div>
{{-- <script>
$(document).ready(function(){
$("#country").change(function(){
var id = this.value;
$("#exampleCountryID").val(id);
// alert(id);
// $.ajax({
// url: "http://127.0.0.1:8000/states",
// type: "POST",
// dataType: "json",
// data: {country_id: id},
// success: function(result){
// if(result) {
// alert("Correct");
// }
// },
// error: function(result){
// if(result) {
// alert("Incorrect");
// }
// }
// });
});
});
</script> --}}
</body>
</html>
Below File is resources\views\statesHome.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Home Screen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-10">
<a href="{{ route("states") }}" class="btn btn-primary mt-5 mb-5">Add New State</a>
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>ID</td>
<td>Country ID</td>
<td>Country Name</td>
<td>Status</td>
<td>Created At</td>
<td>Updated At</td>
</tr>
</thead>
<tbody>
@foreach($data as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->country_ID }}</td>
<td>{{ $value->state_name }}</td>
<td>{{ $value->status }}</td>
<td>{{ $value->created_at }}</td>
<td>{{ $value->updated_at }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Below File is routes\web.php File
<?php
use App\Http\Controllers\CountryController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\StatesController;
use App\Http\Controllers\TaskController;
use App\Http\Controllers\TestController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::controller(NotificationController::class)->group(function () {
Route::get("notification", "indexNotification");
Route::get("notification/{type}", "notification")->name("notification");
Route::get("notification_list", "index_notification");
Route::get("notification_list/{type}", "notification_list")->name("notification_list");
});
Route::controller(TestController::class)->group(function () {
Route::get("/index", "index");
Route::get("/store-session", "storeSession");
Route::get("/delete-session", "deleteSession");
});
Route::get("/welcomeTwoPage", function () {
return view("welcomeTwo");
});
Route::get("/form", function () {
return view("adduser");
})->name("adduser");
Route::post("/add", [UserController::class, "addUser"])->name("addUser");
Route::get("/showAllTasks", [TaskController::class, "showTask"])->name("home.task");
Route::post("/checkValidate", [TaskController::class, "validateUser"])->name("validate.user");
Route::get("/singleTask/{id}", [TaskController::class, "singleTask"])->name("single.task");
Route::get("/updatePage/{id}", [TaskController::class, "updatePage"])->name("update.page");
Route::put("/updateTask/{id}", [TaskController::class, "updateTask"])->name("update.task");
Route::get("/delete/{id}", [TaskController::class, "deleteTask"])->name("delete.task");
Route::controller(CountryController::class)->group(function () {
Route::post("/validateCountry", "validateCountry")->name("validateCountry.country");
Route::get("/countryHome", "showCountry")->name("showCountry.country");
Route::get("/country","index")->name("country");
});
Route::controller(StatesController::class)->group(function () {
Route::post("/validateStates", "validateStates")->name("validateStates.states");
Route::get("/statesHome", "showStates")->name("showStates.states");
Route::get("/states", "index")->name("states");
});
Route::get("/addNew", function () {
return view("adduser");
.png)
.png)
.png)
.png)
Comments
Post a Comment