Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Last active March 6, 2019 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bablukpik/cc44feca99b10d8523493ed4d64989c8 to your computer and use it in GitHub Desktop.
Save bablukpik/cc44feca99b10d8523493ed4d64989c8 to your computer and use it in GitHub Desktop.
//Datatable
++++++++++++Datatable JS+++++++++++
$('#dataTable').DataTable(
{
"processing": true, // Show processing
"serverSide": true, // Server side processing
"ajax":{
url : '<?= route("dataProcessing")?>',
type : "POST",
dataType: 'json',
data:{"_token":"<?php echo csrf_token(); ?>"},
error: function(data){
console.log(data);
}
},
//Style
"aoColumnDefs": [
{ "sWidth": "20%", "aTargets": [ 0 ] }, //<- start from zero
{ "sWidth": "5%", "aTargets": [ 1 ] },
{ "sWidth": "5%", "aTargets": [ 2 ] },
{ 'bSortable': false, 'aTargets': [0,1] } ,
{ className: "dt-center", "aTargets": [0,1,2,3] },
//{ "width": "100px", "targets": [0] }
//{ "width": "20%", "targets": 0 }
],
"columns": [ //4 columns
{'data':'first_name'}
{'data':'last_name'},
{'data':'dob'},
{ "visible": false }, //The id column will be invisible
{"data":"action","searchable":false,"orderable":false}
],
});
$( ".dataTables_length select option:first" ).attr("selected","selected");
//Other Options
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], //Select Box
"paging": true, // Allow data to be paged
"lengthChange": false,
"searching": true, // Search box and search function will be actived
"ordering": true,
"info": true,
fixedColumns: true,
"autoWidth": true,
"processing": true, // Show processing
"serverSide": true, // Server side processing
"deferLoading": 0, // In this case we want the table load on request so initial automatical load is not desired
"pageLength": 5, // 5 rows per page
++++++++++++++++-/Datatable JS+++++++++++++
+++++++++++++++++++Datatable Route++++++++
Route::post('user/{group_id}/datatables', ['as' => 'user.datatables','uses'=>'UserController@usersByGroupDatatables']);
OR,
Route::post('/data/users/', 'DatatableCongroller@getUsers')->('dataProcessing');
+++++++++++++++++++-/Datatable Route++++++++
+++++++++++++++++++Datatable controller++++++++
Route::post('/data/users/', 'DatatableCongroller@getUsers')->name('dataProcessing');
public function getUsers(Request $request){
print_r($request->all());
// The columns variable is used for sorting
$columns = array (
// datatable column index => database column name
0 =>'first_name',
1 =>'last_name',
2 =>'dob',
3 =>'id',
4 =>'action',
);
$totalData = User::count(); //Total record
$totalFiltered = $totalData; // No filter at first so we can assign like this
//Offset and Limit
$start = $request->input ( 'start' ); // Skip first start records
$length = $request->input ( 'length' ); // Get length record from start
/*
* Order By
*/
if ($request->has ( 'order' )) {
if ($request->input ( 'order.0.column' ) != '') {
$orderColumn = $columns[$request->input('order.0.column')];
$orderDirection = $request->input ( 'order.0.dir' );
}
}
//Query
$post=User::offset($start)
->limit($length)
->orderBy($orderColumn,$orderDirection)
->get();
/*
* For Data Search Query
*/
if ($request->has ( 'search' )) {
if ($request->input ( 'search.value' ) != '') {
/*
* Seach clause : we only allow to search on first_name, last_name, and id field
*/
//where ( 'users.user_name', 'Like', '%' . $searchTerm . '%' );
$search = $request->input('search.value');
$post = User::where('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%")
->orWhere('id', 'like', "%{$search}%")
->offset($start)
->limit($length)
->orderBy($orderColumn,$orderDirection)
->get();
$totalFiltered=User::where('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%")
->orWhere('id', 'like', "%{$search}%")
->count();
}
}
/*
* We built the structure required by BootStrap datatables
*/
$data = array ();
foreach ($post as $user ) {
$nestedData = array ();
$nestedData ['first_name'] = $user->first_name; //$nestedData [0] = $user->user_name and so on
$nestedData ['last_name'] = $user->last_name;
$nestedData ['dob'] = $user->dob;
$nestedData ['id'] = date('d-m-Y H:i:s', strtotime($user->id));
$nestedData ['action'] ='
<a href="#" class="btn btn-warning btn-xs">Edit</a>
<a href="#" class="btn btn-danger btn-xs">Delete</a>
';
$data [] = $nestedData;
}
/*
* This below structure is required by Datatables
*/
$json_data = array (
"draw" => intval ( $request->input ( 'draw' ) ), // for every request/draw by clientside
"recordsTotal" => intval ( $totalData ), // total number of records
"recordsFiltered" => intval ( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data
);
echo json_encode($json_data);
}
}
+++++++++++++++++++-/Datatable controller++++++++
+++++++++++++++++++Datatable Pagination++++++++
$nestedData [1] = '<small class="label bg-' . $user->display . '">' . $user->email . '</small>';
+++++++++++++++++++-/Datatable Pagination++++++++
//Start navbar active class
<!-- Example on how to set class="active" on active navigation links -->
<!-- These links will always be visible -->
<li class="{{ URI::is( '/') ? 'active' : '' }}">
<a href="{{ URL::to( '/') }}">
Home
</a>
</li>
<li class="{{ URI::is( 'gallery') ? 'active' : '' }}">
<a href="{{ URL::to( 'gallery') }}">
Gallery
</a>
</li>
<!-- Show link to 'account' if authed -->
@if ( Auth::check() )
<li class="{{ URI::is( 'account') ? 'active' : '' }}">
<a href="{{ URL::to( 'account') }}">
Account
</a>
</li>
@endif
<!-- Login/Logout depending on auth state -->
<li class="{{ URI::is( 'account/login') ? 'active' : '' }}">
@if ( Auth::guest() )
{{ HTML::link('account/login', 'Login') }}
@else
{{ HTML::link('account/logout', 'Logout') }}
@endif
</li>
//Using jQuery
<!--Active class-->
<script>
$(document).ready(function(){
$('.nav li').click(function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
});
</script>
//End navbar active class
//htaccess file for root directory But insecure way
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</ifModule>
//For Laravel 5.5 you need following server requirement
PHP >= 7.0.0
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
//Form
<form action="{{ url('contact/submit') }}" method="POST" class="form-inline">
<input name="_token" type="hidden" value="{{ csrf_token() }}" />
<input type="text" class="form-control" name="workName"/>
<input type="submit" class="btn btn-success" value="Save"/>
</form>
//---------------------Start Named Route-------------------------------
->For uses in a form
array('route' => ['reg.update', $allDBdata->user_id],'method'=>'PUT')
array('route' => 'reg.store')
->For uses in a link
route('profile', ['id' => 1])
like user/{id}/profile
//OR
route('user.edit', [$user->id])
like /user/2/edit
//OR
route('article.destroy', $article->id)
->Delete in a Link
{{Form::open(['method' => 'DELETE', 'route' => ['home.destroy', $todo->id]])}}
//OR
<form action="/article/{{$article->id}}" method="post" class="pull-right">{{csrf_field()}} {{method_field("DELETE")}}<button class="btn btn-danger btn-xs"> Delete </button></form>
<form action="/article/'.$article->id.'" method="post" style="display: inline;">'.csrf_field().method_field("DELETE").'<button class="btn btn-danger btn-xs"> Delete </button></form>
++++++++
Route::get('aboutUs', function() {
return view('pages.about');
})->name('about');
// Or using a controller:
Route::get('aboutUs', 'PageController@showAbout')->name('about');
//And Link:
<a href="{{ route('about') }}">About us</a>
//Absolute URL
<a href="{{ route('posts.show', [$id]) }}">Link to Resource {{ $id }}</a>
For example: http://example.com/posts/10
//Relative URL
<a href="{{ route('posts.show', [$id], false) }}">Link to Resource {{ $id }}</a>
For example: /posts/10
//if we don't need any controller
Route::view('/welcomee', 'welcome', ['name' => 'Taylor']);
// Define route in `routes/web.php`
Route::get('posts/{post}/comments/{comment}', 'CommentController@show')->name('comment');
//And Create link to named route in Blade
<a href="{{ route('comment', ['1', '2', 'par'=>'HELLO', 'par2'=>'Goodbye']) }}">The Comment</a>
For example:
The generated URL looks like: http://example.com/posts/1/comments/2?par=HELLO&par2=Goodbye
//Using Laravel Collective
{!! Form::open(['method' => 'DELETE',
'route' => ['leads.destroy', $id],
'id' => 'form-delete-lead-' . $id])
!!}
The ‘route’ array is comprised of ‘route.name’ followed by route parameters.
The Redirect::to() method will also accept a named route:
// redirect to http://example.com/leads?ship=Rocinante
return redirect()->route('leads.index', ['ship' => 'Rocinante']);
//--------------------End Named Route---------------------------
//--------------------Start Base URL----------------------------
<a href="{{ url('/path/uri') }}">Link Text</a>
OR
<a href="{{ URL::to('/path/uri') }}">Link Text</a>
OR
asset('/') OR URL::route OR action="{{ action('WelcomeController@log_in') }}"
OR
<form method="post" action="{{route('admin.spway.edit')}}" class="form form-horizontal" id="form-spway-edit">
Other useful functions:
$uri = $request->path();
$url = $request->url();
$url = $request->fullUrl();
asset()
app_path();
php artisan route:list
//Seed or Seeding in Laravel
v.01
class UsersTablesSeeder extends Seeder
{
User::create([
'name' => 'John Smith',
'email' => 'john_smith@gmail.com',
'password' => Hash::make('password'),
'remember_token' => str_random(10),
]);
}
Then,
class DatabaseSeeder extends Seeder
public function run()
{
Eloquent::unguard();
$this->call(UsersTablesSeeder::class);
}
v.02
//--------------------------End Base URL---------------------------
//--------------------------Start Auth Routes----------------------
In routes\web.php file, replace the Auth::routes(); with the following:
// Authentication Routes...
$this->get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('admin/login', 'Auth\LoginController@login');
$this->post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
$this->get('admin/register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('admin/register', 'Auth\RegisterController@register');
// Password Reset Routes...
$this->get('admin/password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
$this->post('admin/password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
$this->get('admin/password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
$this->post('admin/password/reset', 'Auth\ResetPasswordController@reset');
//--------------------------End Auth Routes----------------------
//--------------------------Start Select for edit----------------------
<select id="category_id" class="form-control col-md-7 col-xs-12 selectpicker" name="category_id[]" data-live-search="true" required="required" multiple data-selected-text-format="count > 3">
@if (count($category_id) > 0)
@foreach($category_id as $id)
<option value="{{ $id }}" {{ $id ? 'selected="selected"' : '' }} data-tokens="@if($id==1) hi @elseif($id==2) Ba @elseif($id==3) Ha @elseif($id==4) Ha @endif">
@if($id==1)
hi
@elseif($id==2)
Ba
@elseif($id==3)
Ha
@elseif($id==4)
Ha
@endif
</option>
@endforeach
@endif
<option value="1" data-tokens="hi">hi</option>
<option value="2" data-tokens="Ba">Ba</option>
<option value="3" data-tokens="Ha">Ha</option>
<option value="4" data-tokens="Ha">Ha</option>
</select>
//--------------------------End Select for edit----------------------
//--------------------------Active class----------------------
@forelse($categories as $category)
<li class="{{ Request::path() == 'blog/'.$category->slug ? 'active' : '' }}" ><a href="/blog/{{ $category->slug }}">{{ $category->category_name }}</a></li>
@empty
<p>No category found!</p>
@endforelse
//OR
You can also use * as wildcard:
<li{{ request()->is('scam-type-number-*') ? ' class="active"' : '' }}>
//OR
<li class="{{ Request::is('/')?'active':'' }}"><a href="{{ url('/') }}">Home</a></li>
OR
{{Request::segment(1)}}
//--------------------------/Active class----------------------
<!--Logout Button-->
<a data-toggle="tooltip" data-placement="top" title="Logout" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
<span class="glyphicon glyphicon-off" aria-hidden="true"></span>
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
<!--/Logout Button-->
//...................................Service Container/Provider...............................
https://stackoverflow.com/questions/52088908/where-to-find-service-containers-in-a-laravel-project
https://medium.com/@NahidulHasan/laravel-ioc-container-why-we-need-it-and-how-it-works-a603d4cef10f
<?php
/*
Global methods:
view();
request();
app();
*/
/*
* Service Container:
*
* Class registration with Service Container (App Class or $app instance)
*
For Example:
1.
App::bind('App\Billing\Stripe', function(){
return new \App\Billing\Stripe(config('services.stripe.secret'));
});
2.
App::singleton('App\Billing\Stripe', function(){
return new \App\Billing\Stripe(config('services.stripe.secret'));
});
i.e,
$stripe = resolve('App\Billing\Stripe');
$stripe2 = resolve('App\Billing\Stripe');
$stripe3 = resolve('App\Billing\Stripe');
3.
App:instance('App\Billing\Stripe', $stripe);
*/
App::bind('App\Billing\Stripe', function(){
return new \App\Billing\Stripe(config('services.stripe.secret'));
});
/*
* Now resolve the class and make an instance of the class using one of the following methods
*
i) App::make();
ii) resolve();
iii) app();
For Example:
$stripe = App::make('App\Billing\Stripe');
$stripe = resolve('App\Billing\Stripe');
$stripe = app('App\Billing\Stripe');
*/
$stripe = App::make('App\Billing\Stripe');
dd($stripe);
/*
N.B, This is happening in the web.php file but this is not right so where should place this Service Container that's why we need a service provider
*/
/*
* Create a class called Stripe in the app/billing directory (you can make anywhere in your application) like this
*
namespace App\Billing;
class Stripe
{
protected $key;
public function __construct($key) {
$this->key = $key;
}
}
*/
//--------------------------------Strict Mode For Group By------------------------------
Change this line in mysql array of config/database.php
'strict' => true,
To
'strict' => false,
Or
Before coding add following line:
DB::statement("SET sql_mode = '' ");
//SET sql_mode = '';
Or
SET GLOBAL sql_mode = 'modes';
SET SESSION sql_mode = 'modes';
Link: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment