VIDEO
9 laravel card component table
VIDEO
card create
edit
delete
shbow
whats the input fields
type of account (it is savings or loan ro deposit)
bank name
bank account id
bank ifsc code
formulkal
description
on delete confirmation mdoels or popup with validations
after done everytinng we are shoiwing in tabular form
with error and succces mesages
php artisan make:model Card --mvc
composer dump-autoload
composer install
composer update
whatever the cloumns we need that is fillable in model
we can validate validations at controller or at model
or request also popssible
at model
<?php
namespace App\Models ;
use Illuminate\Database\Eloquent\Factories\ HasFactory ;
use Illuminate\Database\Eloquent\ Model ;
class Card extends Model
{
use HasFactory ;
protected $fillable = [
'account_type' ,
'name' ,
'description' ,
'formula' ,
'upi_id' ,
// Add other attributes here if needed
];
public static $rules = [
'account_type' => 'required|in:savings,credit_card,loan' ,
'name' => 'required|string|max:255' ,
'description' => 'nullable|string' ,
'formula' => 'nullable|string' ,
'upi_id' => 'required|string|max:255' ,
];
// Custom error messages
public static $messages = [
'account_type.required' => 'The account type field is required.' ,
'account_type.in' => 'The account type must be one of: savings, credit_card, loan.' ,
'name.required' => 'The name field is required.' ,
'name.max' => 'The name may not be greater than :max characters.' ,
'description.string' => 'The description must be a string.' ,
'formula.string' => 'The formula must be a string.' ,
'upi_id.required' => 'The UPI ID field is required.' ,
'upi_id.max' => 'The UPI ID may not be greater than :max characters.' ,
];
}
at controller
$validatedData = $request -> validate ([
'category_id' => 'required|numeric|exists:categories,id' ,
'sub_category_id' => 'required|numeric|exists:sub_categories,id' ,
'title' => 'string|required|unique:blogs,title,NULL,id,deleted_at,NULL' ,
'slug' => 'required|unique:blogs,slug,NULL,id,deleted_at,NULL' ,
'description' => 'nullable|string|max:65535' ,
'blog_for' => 'required|numeric|exists:blog_for_options,id' ,
'tags' => 'nullable|string|max:255' ,
'meta_tags' => 'nullable|string|max:255' ,
'meta_description' => 'nullable|string|max:255' ,
'image_alt' => 'nullable|string|max:255' ,
'save_type' => 'required|in:draft,submit'
// 'mins_read' => 'nullable|numeric',
]);
at request
<?php
namespace App\Http\Requests ;
use Illuminate\Foundation\Http\ FormRequest ;
use App\Http\Traits\ PermissionTrait ;
class SomeRequest extends FormRequest
{
// use PermissionTrait;
public function authorize ()
{
// switch ($this->getMethod()) {
// case 'GET': // Get
// return $this->hasOnePermission('view:team');
// case 'POST': // Create
// return $this->hasOnePermission('create:team');
// case 'PUT': // Update
// return $this->hasOnePermission('edit:team');
// case 'DELETE': // Delete
// return $this->hasOnePermission('delete:team');
// }
return true ;
}
public function rules ()
{
switch ( $this -> getMethod ()) {
case 'GET' : // Create
return [
'id' => 'integer|exists:teams,id' ,
'per_page' => 'integer|in:1,5,10,25,50,100' ,
];
case 'POST' : // Create
return [
'name' => 'required|string|min:2|max:255|unique:teams,name' ,
'manager' => 'array' ,
'manager.*' => 'exists:users,id' ,
'member' => 'array' ,
'member.*' => 'exists:users,id' ,
];
case 'PUT' : // Update
return [
'id' => 'required|integer|exists:teams,id' ,
'name' => 'required|string|min:2|max:255|unique:teams,name,' . $this -> id ,
'manager' => 'array' ,
'manager.*' => 'exists:users,id' ,
'member' => 'array' ,
'member.*' => 'exists:users,id' ,
];
case ' DELETE ' : // Delete
return [
'id' => 'required|integer|exists:teams,id' ,
];
}
}
public function messages ()
{
return [
'id.integer' => 'id must be an integer.' ,
'id.required' => 'The ID is required.' ,
'id.exists' => 'The selected ID does not exist in the Teams table.' ,
'per_page.integer' => 'The "per_page" value must be an integer.' ,
'per_page.in' => 'The selected "per_page" value is invalid. Please choose from the available options: 1, 5, 10, 25, 50, or 100.' ,
'name.required' => 'Name is required.' ,
'name.string' => 'Name must be a string.' ,
'name.min' => 'Name must be at least :min characters long.' ,
'name.max' => 'Name must not exceed :max characters.' ,
'name.unique' => 'Name is already taken by another team.' ,
'manager.array' => 'Manager must be an array.' ,
'manager.*.exists' => 'Manager ID ":input" does not exist in the teams.' ,
'member.array' => 'Member must be an array.' ,
'member.*.exists' => 'Member ID ":input" does not exist in the teams.' ,
];
}
}
return response
we candirectly return
return response ()-> json ([
'success' => true ,
'data' => $blog ,
'message' => 'Blog retrieved successfully.' ,
]);
=
return redirect ()-> route ( 'home' );
=
return view (VIEW_FILE_NAMES[ 'flash_deals' ], compact ( 'deal' , 'discountPrice' ));
through resource
<?php
namespace App\Http\Resources ;
use Illuminate\Http\Resources\Json\ ResourceCollection ;
class TeamResourceCollection extends ResourceCollection
{
protected $rowsCount ;
public function __construct ( $resource , $rowsCount = null )
{
parent :: __construct ( $resource );
$this -> rowsCount = $rowsCount ;
}
public function toArray ( $request )
{
return [
'data' => TeamResource :: collection ( $this -> collection ),
'pagination' => [
'current_page' => $this -> currentPage (),
'per_page' => $this -> perPage (),
'total' => $this -> total (),
'last_page' => $this -> lastPage (),
'rows_count' => $this -> rowsCount ,
],
];
}
}
====
<?php
namespace App\Http\Resources ;
use Illuminate\Http\Resources\Json\ JsonResource ;
class TeamResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\ Request $request
* @return array |\Illuminate\Contracts\Support\ Arrayable | \JsonSerializable
*/
public function toArray ( $request )
{
return [
'id' => $this -> id ,
'name' => $this -> name ,
'created_at' => $this -> created_at ,
'user_has_team_manager_count' => $this -> user_has_team_manager_count ,
'user_has_team_member_count' => $this -> user_has_team_member_count ,
'user_has_team_member' => UserHasTeamMemberResource :: collection ( $this -> whenLoaded ( 'user_has_team_member' )),
'user_has_team_manager' => UserHasTeamManagerResource :: collection ( $this -> whenLoaded ( 'user_has_team_manager' )),
];
}
}
====
<?php
namespace App\Http\Resources ;
use Illuminate\Http\Resources\Json\ JsonResource ;
class UserHasTeamManagerResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\ Request $request
* @return array |\Illuminate\Contracts\Support\ Arrayable | \JsonSerializable
*/
public function toArray ( $request )
{
return [
'id' => $this -> id ,
'team_id' => $this -> team_id ,
'team_type' => $this -> team_type ,
'user_id' => $this -> user_id ,
'user' => new UserResource ( $this -> whenLoaded ( 'user' )),
];
}
}
list of migrations
$table -> string ( 'cm_firebase_token' )-> nullable ();
list of laravel migrations
Textual Types $table->char('name', 100);
: A fixed-length string (100 characters in this example).$table->string('name', 255);
: A variable-length string (255 characters is the default).$table->text('description');
: A text column for longer text.$table->mediumText('description');
: A medium-length text column.$table->longText('description');
: A long-length text column.Integer Types $table->tinyInteger('votes');
: A tiny integer column.$table->smallInteger('votes');
: A small integer column.$table->mediumInteger('votes');
: A medium integer column.$table->integer('votes');
: A standard integer column.$table->bigInteger('votes');
: A big integer column.Decimal Types $table->float('amount', 8, 2);
: A float column.$table->double('amount', 8, 2);
: A double column with precision (8) and scale (2).$table->decimal('amount', 8, 2);
: A decimal column with precision (8) and scale (2).Boolean Type $table->boolean('confirmed');
: A boolean column.Schema :: table ( 'order_details' , function ( Blueprint $table ) {
$table -> boolean ( 'is_stock_decreased' )-> default ( 1 );
});
Date and Time Types $table->date('created_at');
: A date column.$table->dateTime('created_at', 0);
: A datetime column with precision (0).$table->dateTimeTz('created_at', 0);
: A datetime column with timezone.$table->time('sunrise', 0);
: A time column with precision (0).$table->timeTz('sunrise', 0);
: A time column with timezone.$table->timestamp('added_on', 0);
: A timestamp column with precision (0).$table->timestampTz('added_on', 0);
: A timestamp column with timezone.$table->timestamps(0);
: Shortcut for creating both created_at
and updated_at
columns.$table->timestampsTz(0);
: Timestamps with timezone.$table->softDeletes();
: Shortcut for a deleted_at
column for soft deletes.$table->softDeletesTz();
: deleted_at
with timezone for soft deletes.$table->year('birth_year');
: A year column.Binary Type $table->binary('data');
: A binary column.Miscellaneous Types $table->uuid('id');
: A UUID column.$table->ipAddress('visitor');
: An IP address column.$table->macAddress('device');
: A MAC address column.$table->json('options');
: A JSON column.$table->jsonb('options');
: A JSONB column (similar to JSON but stored in a binary format).$table->geometry('positions');
: A geometry column for spatial data.$table->point('location');
: A point column for spatial data.$table->lineString('positions');
: A linestring column for spatial data.$table->polygon('positions');
: A polygon column for spatial data.$table->geometryCollection('positions');
: A geometry collection column for spatial data.$table->multiPoint('positions');
: A multipoint column for spatial data.$table->multiLineString('positions');
: A multilinestring column for spatial data.$table->multiPolygon('positions');
: A multipolygon column for spatial data.$table->enum('level', ['easy', 'medium', 'hard']);
$table->set('flavors', ['sweet', 'sour', 'bitter']);
: Similar to an enum, but a set
type column can hold zero or more values from the predefined list. This type is specific to MySQL and may not be supported by Laravel's schema builder directly. Usage might require raw statements or be handled through custom migration logic.
Enum Type $table->enum('level', ['easy', 'medium', 'hard']);
: An enumeration, which is a column that can hold one value out of a list of predefined values. In this case, the level
column can only contain the values 'easy'
, 'medium'
, or 'hard'
.Set Type (Specific to MySQL) $table->set('flavors', ['sweet', 'sour', 'bitter']);
: Similar to an enum, but a set
type column can hold zero or more values from the predefined list. This type is specific to MySQL and may not be supported by Laravel's schema builder directly. Usage might require raw statements or be handled through custom migration logic.Additional Date and Time Types While I covered the basic date and time types, Laravel also supports more granular temporal types, especially useful when you need to store values without timezone information or with more precision:
$table->date('event_date');
: Just to reiterate, stores a date without time.$table->dateTime('event_time', $precision);
: Stores date and time, with optional precision.$table->time('opening_hours', $precision);
: Stores time only, with optional precision.$table->year('manufacture_year');
: Stores a year (4 digits).Remember Token $table->rememberToken();
: Adds a nullable remember_token
column of type VARCHAR(100)
. This is particularly useful for storing a token used by Laravel to "remember" the user session in a cookie.Increment and Decrement Types $table->increments('id');
: An auto-incrementing unsigned integer (primary key).$table->bigIncrements('id');
: An auto-incrementing unsigned big integer (primary key).Morphs Laravel also includes types that are helpful for setting up polymorphic relationships within your database schema:
$table->morphs('taggable');
: Adds taggable_id
unsignedBigInteger and taggable_type
string columns. Useful for polymorphic relationships.$table->uuidMorphs('taggable');
: Similar to morphs
but uses UUIDs.$table->nullableMorphs('taggable');
: Adds nullable polymorphic relationship columns to the table.$table->foreignIdMorphs('taggable');
: Adds polymorphic relationship columns designed to be foreign keys.Foreign ID Convenience Methods For defining foreign keys, Laravel provides some convenience methods as well:
$table->foreignId('user_id');
: Shortcut for creating an unsigned big integer column that is meant to be a foreign key.$table->foreignUuid('user_id');
: Creates a UUID equivalent intended to be used as a foreign key.migration structure
<?php
use Illuminate\Database\Migrations\ Migration ;
use Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Support\Facades\ Schema ;
class CreateProductTranslationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up ()
{
Schema :: create ( 'translations' , function ( Blueprint $table ) {
$table -> bigInteger ( 'id' );
$table -> string ( 'translationable_type' );
$table -> unsignedBigInteger ( 'translationable_id' )-> index ();
$table -> string ( 'locale' )-> index ();
$table -> string ( 'key' )-> nullable ();
$table -> text ( 'value' )-> nullable ();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down ()
{
Schema :: dropIfExists ( 'translations' );
}
}
php artisan migrate ( it will run up)
php artisan migrate:rollback --step=1 (it will run down)
php artisan make:migration add_mobile_column_to_users_Table --table = users
$table -> float ( 'order_amount' )-> change ();
modifiers
along with the column types, there are also several important column modifiers in Laravel migrations that allow you to further specify details about each column, such as setting default values, making columns nullable, adding indexes, and more. Let's go over some of these common column modifiers:
Default Values $table->string('name')->default('John Doe');
: Sets the default value for the column.Nullable $table->string('nickname')->nullable();
: Allows the column to contain NULL
values.Unique $table->string('email')->unique();
: Ensures that all values in the column are unique across the table.Indexes $table->string('email')->index();
: Adds an index to the column to improve query performance on that column.$table->index(['account_id', 'created_at']);
: Creates an index for multiple columns.Primary Key $table->id();
or $table->increments('id');
: Creates an auto-incrementing ID (primary key) column.$table->primary('id');
: Defines a column as the primary key.Foreign Key Constraints $table->foreignId('user_id')->constrained();
: Adds an unsigned big integer column and defines a foreign key constraint that references the id
column on the users table.$table->foreign('user_id')->references('id')->on('users');
: The manual way to define a foreign key constraint.Changing Columns To modify an existing column, you first need to install the doctrine/dbal
package. Once installed, you can use the change
modifier:$table->string('name', 50)->change();
: Changes the definition of an existing column. For example, changing the length of a string column. Nullable and Default Together $table->string('middle_name')->nullable()->default(null);
: Makes a column nullable and explicitly sets the default value to NULL
.Setting Column After Another Column $table->string('middle_name')->after('first_name');
: Places the new column after another specified column (MySQL specific).Dropping Columns $table->dropColumn('votes');
: Removes a column from the table.For dropping multiple columns: $table->dropColumn(['votes', 'avatar', 'location']);
Timestamps $table->timestamps();
: Adds nullable created_at
and updated_at
columns.$table->nullableTimestamps();
: Explicitly adds nullable timestamps.$table->timestampsTz();
: Adds nullable timestamps with timezone.Soft Deletes $table->softDeletes();
: Adds a nullable deleted_at
column for soft deletes.$table->softDeletesTz();
: Adds a nullable deleted_at
column with timezone for soft deletes.Remember Token $table->rememberToken();
: Adds a nullable remember_token
column for user authentication tokens.
closure usage
$deal = FlashDeal :: with ([ 'products.product.reviews' , 'products.product' =>
function ( $query ){
$query -> active ();
}])
-> where ([ 'id' => $id , 'status' => 1 ])
-> whereDate ( 'start_date' , '<=' , date ( 'Y-m-d' ))
-> whereDate ( 'end_date' , '>=' , date ( 'Y-m-d' ))
-> first ();
$discountPrice = FlashDealProduct :: with ([ 'product' ])
-> whereHas ( 'product' , function ( $query ) {
$query -> active ();
})-> get ()-> map ( function ( $data ) {
return [
'discount' => $data -> discount ,
'sellPrice' => isset ( $data -> product -> unit_price )
? $data -> product -> unit_price : 0 ,
'discountedPrice' => isset ( $data -> product -> unit_price )
? $data -> product -> unit_price - $data -> discount : 0 ,
];
})-> toArray ();
if ( isset ( $deal )) {
return view (VIEW_FILE_NAMES[ 'flash_deals' ],
compact ( 'deal' , 'discountPrice' ));
}
Toastr :: warning ( translate ( 'not_found' ));
return back ();
usage of sesions
session ()-> put ( 'product_brand' , $brand_status );
if ( session ()-> has ( 'default' )) {
$default = session ( 'default' );
} else {
$default = Currency :: find ( Helpers :: get_business_settings ( 'system_default_currency' ))-> exchange_rate ;
session ()-> put ( 'default' , $default );
}
if ( session ()-> has ( 'usd' )) {
$usd = session ( 'usd' );
} else {
$usd = Currency :: where ( 'code' , 'USD' )-> first ()-> exchange_rate ;
session ()-> put ( 'usd' , $usd );
}
session ()-> forget ( 'coupon_code' );
session ()-> flash ( 'error' , 'Database error!' );
ternary operator
session ()-> has ( 'coupon_discount' ) ? session ( 'coupon_discount' ) : 0 ;
The ternary operator (?:
) and the null coalescing operator (??
) are both conditional operators used in programming languages like PHP. They serve similar purposes in some contexts but have distinct functionalities.
Ternary Operator (Conditional Operator) The ternary operator (?:
) is a concise way to write an if-else statement in a single line. It has the following syntax:
(condition) ? (expression if true ) : (expression if false );
Here's an example in PHP:
$age = 25 ;
$message = ($age >= 18 ) ? "You are an adult." : "You are a minor." ;
echo $message ;
In this example, if the condition $age >= 18
is true, it assigns the string "You are an adult." to the variable $message
; otherwise, it assigns "You are a minor."
Null Coalescing Operator The null coalescing operator (??
) is used to provide a default value for a variable if the variable is null or not set. It has the following syntax:
$variable = $value ?? $default_value ;
Here's an example in PHP:
$username = $input_username ?? "Guest" ;
echo $username ;
In this example, if $input_username
is null or not set, it assigns the string "Guest" to the variable $username
; otherwise, it assigns the value of $input_username
.
Differences Usage :
The ternary operator is used for conditional expressions, where you want to choose between two values based on a condition. The null coalescing operator is used for providing a default value when a variable is null or not set. Default Value Handling :
Ternary Operator: Requires explicitly providing both the true and false expressions. Null Coalescing Operator: Requires providing only the default value that will be used if the variable is null or not set. Condition Checking :
Ternary Operator: Checks a condition to determine which expression to evaluate. Null Coalescing Operator: Checks if a variable is null or not set and provides a default value accordingly. Return Values :
Ternary Operator: Returns one of two possible values based on the condition. Null Coalescing Operator: Always returns a value, either the variable value or the default value. Here's a quick comparison to illustrate:
$message = ($isLoggedIn ) ? "Welcome back!" : "Please log in." ;
$username = $input_username ?? "Guest" ;
In summary, the ternary operator is used for conditional expressions, while the null coalescing operator is specifically for handling null or unset values by providing a default value. Both are valuable tools for writing concise and expressive code.
if an y blade develop if possible it will reuseful inour project
app.blade.php
@include('layouts.navbar)
@yield('content')
@stack('scripts')
at card/index
new styles
@push('styles')
@endpush
<!-- resources/views/cards/index.blade.php -->
@extends('layouts.app')
@section('content')
< div class ="container" >
< nav aria-label ="breadcrumb" >
< ol class ="breadcrumb" >
< li class ="breadcrumb-item active" aria-current ="page" > Cards</ li >
</ ol >
</ nav >
< div class ="d-flex justify-content-end" >
< button type ="button" class ="btn btn-primary" data-toggle ="modal" data-target ="#myModal" >
Bulk Upload
</ button >
< a href ="{{ route('cards.create') }}" class ="btn btn-primary ml-2" > Create Card</ a >
</ div >
@include('layouts.error')
<!-- Button to trigger modal -->
@php
$headers = [
['label' => 'Name', 'key' => 'name', 'sort_by' => true],
['label' => 'Description', 'key' => 'description', 'sort_by' => true],
['label' => 'Actions', 'key' => 'actions', 'sort_by' => false,'action'=>['edit','delete']],
];
$sort_by = '';
$api_url='cards';
@endphp
@include('components.data-table', ['headers' => $headers, 'ap_url' => $api_url,'sort_by'=>$sort_by])
</ div >
<!-- Modal -->
< div class ="modal fade" id ="myModal" tabindex ="-1" role ="dialog" aria-labelledby ="myModalLabel" aria-hidden ="true" >
@php
$elements = [
[
'method'=>'input',
'label' => 'Choose File',
'key' => 'file_input',
'place_holder' => 'Choose File',
'type' => 'file',
'required'=>true,
'readonly'=>false
],
];
$modal_name='Upload File';
$action_name='Upload';
$route_name='import_users';
@endphp
@include('components.modal-form', ['elements' => $elements,'modal_name'=>$modal_name,'action_name'=>$action_name,'route_name'=>$route_name])
</ div >
@endsection
< script >
</ script >
=
componment
data-table
@if (!isset($headers) || !isset($api_url))
< div class ="alert alert-danger" role ="alert" >
Headers for the table and API URL are required.
</ div >
@else
< div class ="row mt-2" >
< div class ="col-3 d-flex align-items-center" >
< label for ="sel1" class ="form-label me-2 col-2" > Display </ label >
< select class ="form-select me-2" id ="sel1" name ="sellist1" >
< option selected > 10</ option >
< option > 25</ option >
< option > 50</ option >
< option > 100</ option >
</ select >
< label for ="sel1" class ="form-label col-2" > Results </ label >
</ div >
< div class ="col-3" ></ div >
< div class ="col-6" >
< form id ="search-form" class ="d-flex" >
< div class ="input-group" >
< input type ="text" id ="search-input" class ="form-control" placeholder ="Search..." aria-label ="Search for cards" >
< button type ="button" id ="search-button" class ="btn btn-primary" > Search</ button >
< button type ="button" id ="clear-search" class ="btn btn-danger" >
clear
</ button >
</ div >
</ form >
</ div >
</ div >
< div id ="cards-table" >
< table class ="table table-hover" >
< thead >
< tr >
@foreach ($headers as $header)
< th @if ($header[ 'sort_by']) data-key ="{{ $header['key'] }}" onclick =" toggleSort ('{{ $header[' key '] }}')" @endif >
{{ $header['label'] }}
@if($header['sort_by'])
< i class ="fas fa-sort" ></ i >
@endif
</ th >
@endforeach
</ tr >
</ thead >
< tbody id ="cards-table-body" >
<!-- Cards will be dynamically loaded here -->
</ tbody >
</ table >
</ div >
< div class ="row" >
< div class ="col-3" >
Showing < span id ="from_entries" ></ span > to < span id ="to_entries" ></ span > of < span id ="total_entries" ></ span > entries
</ div >
< div class ="col-3" >
</ div >
< div class ="col-6 d-flex justify-content-end" id ="pagination-links" >
</ div >
</ div >
<!-- Modal for confirmation -->
< div class ="modal fade" id ="confirmDeleteModal" tabindex ="-1" role ="dialog" aria-labelledby ="confirmDeleteModalLabel" aria-hidden ="true" >
< div class ="modal-dialog" role ="document" >
< div class ="modal-content" >
< div class ="modal-header" >
< h5 class ="modal-title" id ="confirmDeleteModalLabel" > Confirm Delete</ h5 >
< button type ="button" class ="close" data-dismiss ="modal" aria-label ="Close" >
< span aria-hidden ="true" > × </ span >
</ button >
</ div >
< div class ="modal-body" >
Are you sure you want to delete this card?
</ div >
< div class ="modal-footer" >
< button type ="button" class ="btn btn-secondary" data-dismiss ="modal" > Cancel</ button >
< form id ="deleteForm" method ="POST" action ="" >
@csrf
@method('DELETE')
< button type ="submit" class ="btn btn-danger" > Delete</ button >
</ form >
</ div >
</ div >
</ div >
</ div >
< script >
// Function to load cards data
// Function to load cards data
function loadCards ( page = 1 , search = '' , per_page = 10 , sort_order = 'asc' , sort_by = 'id' ) {
$ ( ".error-update" ). empty ();
$ ( ".error-update-alert" ). hide ();
$ . ajax ({
url: '{{ $api_url }}' ,
type: 'GET' ,
data: {
page: page ,
search: search ,
per_page: per_page ,
sort_by: '{{$sort_by}}' ? '{{$sort_by}}' : sort_by ,
order: sort_order
},
success : function ( response ) {
// Clear existing table body content
$ ( '#cards-table-body' ). html ( '' );
updateTableHeaders ( sort_by , sort_order );
// Populate table with new data
var html = '' ;
$ . each ( response . data , function ( index , data ) {
html += '<tr>' ;
// Loop through headers to dynamically generate table columns
@ foreach ( $headers as $header )
// Check if the current header is not 'actions'
@ if ( $header [ 'key' ] != 'actions' )
html += '<td>' + data [ '{{$header["key"]}}' ] + '</td>' ;
@ else
// Check if 'actions' column should be included
@ if ( $header [ 'key' ] == 'actions' )
html += '<td>' ;
// Check if 'edit' action is present
@ if ( in_array ( 'edit' , $header [ 'action' ]))
html += '<a href="/admin/{{ $api_url }}/' + data . id + '/edit" class="btn btn-primary"><i class="fas fa-pen"></i></a>' ;
@ endif
// Check if 'delete' action is present
@ if ( in_array ( 'delete' , $header [ 'action' ]))
html += '<button type="button" class="btn btn-danger" onclick="openConfirmDeleteModal(' + data . id + ')"><i class="fas fa-trash"></i></button>' ;
@ endif
html += '</td>' ;
@ endif
@ endif
@ endforeach
html += '</tr>' ;
});
$ ( '#cards-table-body' ). html ( html );
// Clear existing pagination links
$ ( '#pagination-links' ). html ( '' );
// Populate pagination links with new data
html = '<nav aria-label="Page navigation"><ul class="pagination">' ;
$ . each ( response . links , function ( index , link ) {
if ( link . url ) {
html += '<li class="page-item' + ( link . active ? ' active' : '' ) + '"><a class="page-link" href="' + link . url + '">' + link . label + '</a></li>' ;
} else {
html += '<li class="page-item disabled"><span class="page-link">' + link . label + '</span></li>' ;
}
});
html += '</ul></nav>' ;
$ ( '#pagination-links' ). html ( html );
$ ( '#from_entries' ). text ( response . from );
$ ( '#to_entries' ). text ( response . to );
$ ( '#total_entries' ). text ( response . total );
},
error : function ( xhr ) {
if ( xhr . status === 422 ) {
var errors = xhr . responseJSON . errors ;
$ . each ( errors , function ( field , errorMessages ) {
$ ( ".error-update-alert" ). show ();
if ( Array . isArray ( errorMessages )) {
$ ( "#errorMessage" ). text ( errorMessages [ 0 ]);
} else {
$ ( "#errorMessage" ). text ( errorMessages [ 0 ]);
}
});
} else {
console . log ( "Something went wrong. Please contact the support team:" , xhr . statusText );
}
}
});
}
function updateTableHeaders ( sort_by , sort_order ) {
// console.log(sort_by);
// console.log(sort_order);
$ ( 'th' ). each ( function () {
var columnKey = $ ( this ). attr ( 'data-key' );
if ( columnKey === sort_by ) {
if ( sort_order === 'asc' ) {
$ ( this ). find ( 'i' ). removeClass ( 'fa-sort fa-sort-down' ). addClass ( 'fa-sort-up' );
} else {
$ ( this ). find ( 'i' ). removeClass ( 'fa-sort fa-sort-up' ). addClass ( 'fa-sort-down' );
}
} else {
$ ( this ). find ( 'i' ). removeClass ( 'fa-sort-up fa-sort-down' ). addClass ( 'fa-sort' );
}
});
}
var sort_by = '' ;
var sort_order = '' ;
function toggleSort ( header ) {
if ( sort_by === header ) {
sort_order = ( sort_order === 'asc' ) ? 'desc' : 'asc' ;
} else {
sort_by = header ;
sort_order = 'asc' ;
}
loadCards ( 1 , '' , 10 , sort_order , header );
}
function openConfirmDeleteModal ( cardId ) {
$ ( '#confirmDeleteModal' ). modal ( 'show' );
$ ( '#deleteForm' ). attr ( 'action' , '/admin/{{ $api_url }}/' + cardId );
}
// Function to handle pagination clicks
$ ( document ). on ( 'click' , '.pagination a' , function ( e ) {
e . preventDefault ();
var page = $ ( this ). attr ( 'href' ). split ( 'page=' )[ 1 ];
loadCards ( page );
});
$ ( document ). on ( 'click' , '#search-button' , function ( e ) {
e . preventDefault ();
var search = $ ( '#search-input' ). val ();
loadCards ( 1 , search );
});
$ ( document ). on ( 'click' , '#clear-search' , function ( e ) {
$ ( '#search-input' ). val ( '' );
e . preventDefault ();
loadCards ();
});
$ ( document ). on ( 'change' , '#sel1' , function ( e ) {
var per_page = $ ( this ). val ();
e . preventDefault ();
loadCards ( 1 , '' , per_page );
});
// Initial load
$ ( document ). ready ( function () {
loadCards ();
});
</ script >
@endif
component create
@if (!isset($elements))
< div class ="alert alert-danger" role ="alert" >
Elements are required
</ div >
@else
@foreach ($elements as $element)
@if($element['method'] === 'input')
< div class ="form-group mt-2" >
< label for ="{{ $element['key'] }}" >
{{ $element['label'] }}
@if(isset($element['required']) && $element['required'])
< span style =" color: red" > *</ span >
@endif
</ label >
< input
class ="form-control myInput"
autocomplete ="off"
type ="{{ $element['type'] }}"
placeholder ="{{ $element['place_holder'] }}"
name ="{{ $element['key'] }}"
value ="{{ isset($data) ? $data->{$element['key']} : '' }}"
id ="{{ $element['key'] }}"
@if(isset($element[ 'required']) && $element[ 'required']) required @endif
@if(isset($element[ 'readonly']) && $element[ 'readonly']) readonly @endif
>
</ div >
@elseif($element['method'] === 'text-area')
< div class ="form-group mt-2" >
< label for ="{{ $element['key'] }}" >
{{ $element['label'] }}
@if(isset($element['required']) && $element['required'])
< span style =" color: red" > *</ span >
@endif
</ label >
< textarea class ="form-control myInput" placeholder ="{{ $element['place_holder'] }}" id ="{{ $element['key'] }}" name ="{{ $element['key'] }}" @if(isset($element[ 'required']) && $element[ 'required']) required @endif > {{ isset($data) ? $data->{$element['key']} : '' }}</ textarea >
</ div >
@endif
@endforeach
@endif
compoinent model
< div class ="modal-dialog" role ="document" >
< div class ="modal-content" >
<!-- Modal Header -->
< div class ="modal-header" >
< h5 class ="modal-title" id ="myModalLabel" > {{$modal_name}}</ h5 >
< button type ="button" class ="close" data-dismiss ="modal" aria-label ="Close" >
< span aria-hidden ="true" > × </ span >
</ button >
</ div >
<!-- Modal Body -->
< div class ="modal-body" >
<!-- Form to upload file -->
< form method ="POST" action ="{{ route($route_name) }}" enctype ="multipart/form-data" >
@csrf
@include('components.form-elements', ['elements' => $elements])
< button type ="submit" class ="btn btn-primary" > {{$action_name}}</ button >
</ form >
</ div >
<!-- Modal Footer -->
< div class ="modal-footer" >
< button type ="button" class ="btn btn-secondary" data-dismiss ="modal" > Close</ button >
</ div >
</ div >
</ div >
php artisan serve
php artisan key:generate
web.php
api.php
admin.php
csrf protection not requiuired not required for middleware api
routeserviceprovider.pohp
protected $namespace = 'App \\ Http \\ Controllers \\ Web' ;
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot ()
{
$this -> configureRateLimiting ();
$this -> routes ( function () {
Route :: prefix ( 'api' )
-> middleware ( 'api' )
-> namespace ( 'App \\ Http \\ Controllers \\ Api' )
-> group ( base_path ( 'routes/api.php' ));
Route :: middleware ( 'web' )
-> namespace ( $this -> namespace )
-> prefix ( 'admin' )
-> group ( base_path ( 'routes/admin.php' ));
Route :: middleware ( 'web' )
-> namespace ( $this -> namespace )
-> group ( base_path ( 'routes/web.php' ));
});
there is no noeed of everytime callcalling include all routes at initial like of routes.php
authenticatgion
Route :: middleware ([ 'auth:api' ])-> group ( function () {
web.php
Route :: middleware ([ 'auth' ])-> group ( function () {
Route :: get ( '/home' , function () {
return view ( 'home' );
});
card controller
<?php
namespace App\Http\Controllers\Api ;
use Illuminate\Http\ Request ;
use App\Models\ Card ;
use App\Events\ MyEvent ;
class CardController extends Controller
{
public function index ( Request $request )
{
$rules = [
'per_page' => 'integer|in:1,5,10,25,50,100' ,
];
$customMessages = [
'per_page.integer' => 'The per page value must be an integer.' ,
'per_page.in' => 'The per page value must be one of the following: 1, 5, 10, 25, 50, 100.' ,
];
$details = $this -> validate ( $request , $rules , $customMessages );
$data = Card :: query ();
// if ($request->has('query')) {;
// // $columns=$this->fillable;
// // $data->whereIn($columns, function ($query) use ($request) {
// // $query->where('like', '%' . $request->search . '%');
// // });
// }
if ( $request -> has ( 'query' )) {
$searchTerm = $request -> input ( 'query' ); // Access the actual value of 'query' parameter
$data -> where ( 'description' , 'like' , '%' . $searchTerm . '%' );
}
$per_page = $request -> has ( 'per_page' ) ? $details [ 'per_page' ] : 10 ;
if ( $request -> has ( 'sort_by' ) && $request -> has ( 'order' )) {
$data = $data -> orderBy ( $request [ 'sort_by' ], $request [ 'order' ]);
} else {
$data = $data -> orderBy ( 'id' , 'desc' );
}
return response ()-> json ([
'status' => 'success' ,
'message' => 'Fetched Successfully' ,
'data' => $data -> paginate ( $per_page )
], 201 );
}
public function store ( Request $request )
{
$request -> validate ( Card :: $rules , Card :: $messages );
Card :: create ( $request -> all ());
return Card :: orderBy ( 'id' , 'desc' )-> paginate ( 5 );
return response ()-> json ([
'status' => 'success' ,
'message' => 'Card created successfully' ,
'data' => ''
], 201 );
}
public function edit ( Card $card )
{
return response ()-> json ([
'status' => 'success' ,
'message' => 'Data Fetched successfully' ,
'data' => $card
], 201 );
}
public function update ( Request $request , Card $card )
{
// Validate request
$data = $request -> validate ( Card :: $rules , Card :: $messages );
$card -> update ( $request -> all ());
return Card :: orderBy ( 'id' , 'desc' )-> paginate ( 5 );
return response ()-> json ([
'status' => 'success' ,
'message' => 'Data Updated successfully' ,
'data' => ''
], 201 );
}
public function destroy ( Card $card )
{
$card -> delete ();
return Card :: orderBy ( 'id' , 'desc' )-> paginate ( 5 );
return response ()-> json ([
'status' => 'success' ,
'message' => 'Requested Data Delete successfully' ,
'data' => ''
], 201 );
}
}
php artisan route:list to know the routes of this application
routes register
Route :: resource ( 'users' , UserController :: class );
Route :: resource ( 'roles' , RoleController :: class ,[ 'names' => 'admin.roles' ]);
Route :: post ( '/submit_likes' , [ LikeController :: class , 'submitLikes' ]);
Route :: get ( '/blog_admin/{slug}' , [ BlogController :: class , 'get_blog_by_id' ]);
error.blade.php
@if(session('success'))
< div id ="success-alert" class ="alert alert-success alert-dismissible fade show" role ="alert" >
< button type ="button" class ="btn-close" data-bs-dismiss ="alert" aria-label ="Close" ></ button >
{{ session('success') }}
</ div >
@endif
@if(session('failed'))
< div id ="success-alert" class ="alert alert-danger alert-dismissible fade show" role ="alert" >
< button type ="button" class ="btn-close" data-bs-dismiss ="alert" aria-label ="Close" ></ button >
{{ session('failed') }}
</ div >
@endif
@if ($errors->any())
< div class ="alert alert-danger alert-dismissible fade show" >
< button type ="button" class ="btn-close" data-bs-dismiss ="alert" aria-label ="Close" ></ button >
< ul >
@foreach ($errors->all() as $error)
< li > {{ $error }}</ li >
@endforeach
</ ul >
</ div >
@endif
< div class ="alert alert-danger alert-dismissible fade show error-update-alert " style =" display:none;" >
< button type ="button" class ="btn-close" data-bs-dismiss ="alert" aria-label ="Close" ></ button >
< div class ="error-update text-danger" id ="errorMessage" ></ div >
</ div >
cardcontroller php
<?php
namespace App\Http\Controllers\Web ;
use Illuminate\Http\ Request ;
use App\Models\ Card ;
use App\Events\ MyEvent ;
class CardController extends Controller
{
public function index ( Request $request )
{
// \Log::info($request);
// event(new MyEvent(['key' => 'value']));
if ( $request -> ajax ()) {
$rules = [
'per_page' => 'integer|in:1,5,10,25,50,100' ,
];
$customMessages = [
'per_page.integer' => 'The per page value must be an integer.' ,
'per_page.in' => 'The per page value must be one of the following: 1, 5, 10, 25, 50, 100.' ,
];
$details = $this -> validate ( $request , $rules , $customMessages );
$data = Card :: query ();
if ( $request -> has ( 'search' )) {
$data -> where ( 'name' , 'like' , '%' . $request -> search . '%' );
}
$per_page = $request -> has ( 'per_page' ) ? $details [ 'per_page' ] : 10 ;
if ( $request -> has ( 'sort_by' ) && $request -> has ( 'order' )) {
$data = $data -> orderBy ( $request [ 'sort_by' ], $request [ 'order' ]);
} else {
$data = $data -> orderBy ( 'id' , 'desc' );
}
return $data -> paginate ( $per_page );
}
return view ( 'pages.cards.index' );
}
public function create ()
{
return view ( 'pages.cards.create' );
}
public function store ( Request $request )
{
// Validate request
$request -> validate ( Card :: $rules , Card :: $messages );
Card :: create ( $request -> all ());
return redirect ()-> route ( 'cards.index' )-> with ( 'success' , 'Card created successfully.' );
}
public function edit ( Card $card )
{
return view ( 'pages.cards.edit' , compact ( 'card' ));
}
public function update ( Request $request , Card $card )
{
// Validate request
$request -> validate ( Card :: $rules , Card :: $messages );
$card -> update ( $request -> all ());
return redirect ()-> route ( 'cards.index' )-> with ( 'success' , 'Card updated successfully.' );
}
public function destroy ( Card $card )
{
$card -> delete ();
return redirect ()-> route ( 'cards.index' )-> with ( 'success' , 'Card deleted successfully.' );
}
}
roles/create
<!-- resources/views/cards/create.blade.php -->
@extends('layouts.app')
@section('content')
< div class ="container" >
< nav aria-label ="breadcrumb" >
< ol class ="breadcrumb" >
< li class ="breadcrumb-item" >< a href ="{{ route('roles.index') }}" > Roles</ a ></ li >
< li class ="breadcrumb-item active" aria-current ="page" > Create</ li >
</ ol >
</ nav >
< h2 > Create Role</ h2 >
@include('layouts.error')
< form action ="{{ route('roles.store') }}" method ="POST" >
@csrf
@php
$elements = [
['method'=>'input','label' => 'Enter Role Name', 'key' => 'name', 'place_holder' => 'Enter Role Name', 'type' => 'text','required'=>true],
];
@endphp
@include('components.form-elements', ['elements' => $elements])
< button type ="submit" class ="btn btn-primary" > Create</ button >
</ form >
</ div >
@endsection
roles/edit
<!-- resources/views/cards/edit.blade.php -->
@extends('layouts.app')
@section('content')
< div class ="container" >
< nav aria-label ="breadcrumb" >
< ol class ="breadcrumb" >
< li class ="breadcrumb-item" >< a href ="{{ route('roles.index') }}" > Roles</ a ></ li >
< li class ="breadcrumb-item active" aria-current ="page" > Edit</ li >
</ ol >
</ nav >
< h2 > Edit Card</ h2 >
@include('layouts.error')
< form action ="{{ route('roles.update', $role->id) }}" method ="POST" >
@csrf
@method('PUT')
@php
$elements = [
['method'=>'input','label' => 'Enter Role Name', 'key' => 'name', 'place_holder' => 'Enter Role Name', 'type' => 'text','required'=>true],
];
$data=$role;
@endphp
@include('components.form-elements', ['elements' => $elements,'data'=>$data])
@foreach($permissions as $permission)
< div class ="form-check form-switch" >
< input class ="form-check-input" type ="checkbox" role ="switch" id ="{{$permission->id}}" name ="permissions[]" value ="{{$permission->name}}"
@if(collect($role[ 'permissions'])- > contains('name', $permission->name)) checked @endif>
< label class ="form-check-label" for ="{{$permission->id}}" > {{$permission->name}}</ label >
</ div >
@endforeach
< button type ="submit" class ="btn btn-primary" > Update</ button >
</ form >
</ div >
@endsection
==
No comments:
Post a Comment