Thursday, March 27, 2014

jQuery Scroll To Top

In this tutorial We will learn how to add a simple and  fancy cool scroll to top feature using jQuery.

Scroll to top is a very useful feature when you have a long page website. This make your website page scrolling easily.


Preparing HTML Step 1:


Add HTML code to display scroll to top image.

Add this code at bottom of webpage before </body> tag.


<div class="scrolltop"></div>

 


Preparing CSS Step 2:


Add CSS for class scrolltop. And also place a small arrow image scrolltop.png in images folder.


.scrolltop 
display: none;
background: url(img/scrolltop.png) no-repeat;
width: 44px;
height: 44px;
position: fixed;
right: 90px;
bottom: 30px;
cursor: pointer;

 


Preparing jQuery library Step 3:


Call jQuery Library.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

 


Preparing jQuery code Step 4:


Now add following jQuery code.


<script type="text/javascript">
$(document).ready(function()
$(window).scroll(function()
if ($(this).scrollTop() > 80)
$(".scrolltop").fadeIn('slow');

else
$(".scrolltop").fadeOut('slow');

);
$(".scrolltop").click(function()
$("html, body").animate( scrollTop: 0 , 'slow');
);
);
</script>

You have Done!!!


 



jQuery Scroll To Top

Wednesday, March 19, 2014

CSS3 Tooltip effect

Tooltip is a small popup box which opens when you hover any element. This popup box gives some brief information about that element.


In this tutorial, I will add ToolTip effect to Twitter and Facebook social icons


Step 1: HTML


First let’s do HTML part. Get Twitter and Facebook icon, save the icon in images folder. Now use below code.


<a class="tooltip" href="https://twitter.com/TutWorld_Net" rel="me" target="_blank" title="Follow us on Twitter"><img src="twitter.png"/></a>
<a class="tooltip" href="https://www.facebook.com/tutorialworld.net" rel="me" target="_blank" title="Tutorialworld on Facebook"><img src="facebook.png"/></a>

 


Step 2: CSS


Save  this css your  stylesheet


a
text-decoration: none;

img
border: none;


.tooltip
float:left;
margin-right:10px;
width: 64px;


.tooltip:hover



.tooltip:before



.tooltip:hover::before
content:attr(title);
width:180px;
display:block;
position:relative;
background:#747474;
border:1px solid #000000;
padding:6px;
margin: -33px 0 0 -7px;
border-radius: 6px;
color: #fff;

We Have done !!


 


Demo CSS3 Tooltip effect 



CSS3 Tooltip effect

Tuesday, March 18, 2014

Ultimate Guide and tutorial for .htaccess Files

In this tutorial you will find out about the .htaccess file and the power it has to improve your website.


Enabling .htaccess:


.htaccess files are normally enabled by default. This is actually controlled

by the AllowOverride Directive in the httpd.conf file.


# Only allow .htaccess files to override Authorization and Indexes
AllowOverride AuthConfig Indexes

 


.htaccess Code for Error pages


You will probably want to create an error document for codes 404 and 500, at the least 404 since this would give you a chance to handle requests for pages not found. 500 would help you out with internal server errors in any scripts you have running in your website. You may also want to consider ErrorDocuments for 401 – Authorization Required (as in when somebody tries to enter a protected area of your site without the proper credentials), 403 – Forbidden (as in when a file with permissions not allowing it to be accessed by the user is requested) and 400 – Bad Request, which is one of those generic kind of errors that people get to by doing some weird stuff with your URL or scripts.


You can use custom error pages for any error as long as you know its number (like 404 for page not found) by adding the following to your .htaccess file:


ErrorDocument 404 /errors/notfound.html

also you can use others errors page with this htaccess code


ErrorDocument 400 /error404.html
ErrorDocument 401 /error401.html
ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html
ErrorDocument 500 /error500.html

RewriteEngine On it is turn on Rewrite Rules in Apache Server. if you want to turn off, just change the value to off.


RewriteEngine on

Domain Redirection

.htacces code for redirecting yourwebsite.com to www.yourwebsite.com



RewriteCond %HTTP_HOST ^yourwebsite.com
RewriteRule (.*) http://www.yourwebsite.com/$1 [R=301,L]

 



Sub Domain Redirection

Sub domain redirection mapping to folder. Here http://www.yourwebsite.com is connecting towebsite_folder folder.



RewriteCond %HTTP_HOST ^www\.yourwebsite\.com$
RewriteCond %REQUEST_URI !^/website_folder/
RewriteRule (.*) /website_folder/$1

 



Here http://subdomain.yourwebsite.com is connecting to subdomain_folder folder.



RewriteCond %HTTP_HOST ^subdomain\.yourwebsite\.com$
RewriteCond %REQUEST_URI !^/subdomain_folder/
RewriteRule (.*) /subdomain_folder/$1

 



Old Domain Redirection

htaccess code for redirecting old domain(abc.com) to new domain(xyz.com). Live demofglogin.com is now redirecting to oauthlogin.com



RewriteCond %HTTP_HOST ^abc.com
RewriteRule (.*) http://www.xyz.com/$1 [R=301,L]

RewriteCond %HTTP_HOST ^www\.abc\.com
RewriteRule (.*) http://www.abc.com/$1 [R=301,L]

 



 


Hiding File Extension


http://www.yourwebsite.com/index.html


to


http://www.yourwebsite.com/index



RewriteRule ^([^/.]+)/?$ $1.html

 



Password Protection


There are lots of methods to password protecting areas of your website, some server language (such as ASP, PHP or PERL) and client side , such as JavaScript. JavaScript is not as secure or foolproof as a server-side option, a server side challenge/response is always more secure than a client dependant challenge/response. htaccess is about as secure as you can or need to get in everyday life, though there are ways above and beyond even that of htaccess.


For example, a username and password of wsabstract (and I do not recommend having the username being the same as the password), the htpasswd file would look like this:


tutorialworld:y4E7Ep8e7EYV

 


Create a new htaccess file and place the following code in it:


AuthUserFile /usr/local/you/safedir/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic

require user tutorialworld

You can generate a htaccess password here


 


Deny/Allow Certian IP Addresses


In some situations, you may want to only allow people with specific IP addresses to access your site (for example, only allowing people using a particular ISP to get into a certian directory) or you may want to ban certian IP addresses (for example, keeping disruptive memembers out of your message boards)


You can block an IP address by using:


deny from 000.000.000.000

You can allow an IP address by using:


allow from 000.000.000.000

 


 


You can Deny or ban ip from this htaccess ipaddress banning generator


 


Blocking bad bots and site rippers (aka offline browsers)


Below is a useful code block you can insert into.htaccess file for blocking a lot of the known bad bots and site rippers currently out there.


RewriteEngine On 
RewriteCond %HTTP_USER_AGENT ^BlackWidow [OR]
RewriteCond %HTTP_USER_AGENT ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %HTTP_USER_AGENT ^ChinaClaw [OR]
RewriteCond %HTTP_USER_AGENT ^Custo [OR]
RewriteCond %HTTP_USER_AGENT ^DISCo [OR]
RewriteCond %HTTP_USER_AGENT ^Download\ Demon [OR]
RewriteCond %HTTP_USER_AGENT ^eCatch [OR]
RewriteCond %HTTP_USER_AGENT ^EirGrabber [OR]
RewriteCond %HTTP_USER_AGENT ^EmailSiphon [OR]
RewriteCond %HTTP_USER_AGENT ^EmailWolf [OR]
RewriteCond %HTTP_USER_AGENT ^Express\ WebPictures [OR]
RewriteCond %HTTP_USER_AGENT ^ExtractorPro [OR]
RewriteCond %HTTP_USER_AGENT ^EyeNetIE [OR]
RewriteCond %HTTP_USER_AGENT ^FlashGet [OR]
RewriteCond %HTTP_USER_AGENT ^GetRight [OR]
RewriteCond %HTTP_USER_AGENT ^GetWeb! [OR]
RewriteCond %HTTP_USER_AGENT ^Go!Zilla [OR]
RewriteCond %HTTP_USER_AGENT ^Go-Ahead-Got-It [OR]
RewriteCond %HTTP_USER_AGENT ^GrabNet [OR]
RewriteCond %HTTP_USER_AGENT ^Grafula [OR]
RewriteCond %HTTP_USER_AGENT ^HMView [OR]
RewriteCond %HTTP_USER_AGENT HTTrack [NC,OR]
RewriteCond %HTTP_USER_AGENT ^Image\ Stripper [OR]
RewriteCond %HTTP_USER_AGENT ^Image\ Sucker [OR]
RewriteCond %HTTP_USER_AGENT Indy\ Library [NC,OR]
RewriteCond %HTTP_USER_AGENT ^InterGET [OR]
RewriteCond %HTTP_USER_AGENT ^Internet\ Ninja [OR]
RewriteCond %HTTP_USER_AGENT ^JetCar [OR]
RewriteCond %HTTP_USER_AGENT ^JOC\ Web\ Spider [OR]
RewriteCond %HTTP_USER_AGENT ^larbin [OR]
RewriteCond %HTTP_USER_AGENT ^LeechFTP [OR]
RewriteCond %HTTP_USER_AGENT ^Mass\ Downloader [OR]
RewriteCond %HTTP_USER_AGENT ^MIDown\ tool [OR]
RewriteCond %HTTP_USER_AGENT ^Mister\ PiX [OR]
RewriteCond %HTTP_USER_AGENT ^Navroad [OR]
RewriteCond %HTTP_USER_AGENT ^NearSite [OR]
RewriteCond %HTTP_USER_AGENT ^NetAnts [OR]
RewriteCond %HTTP_USER_AGENT ^NetSpider [OR]
RewriteCond %HTTP_USER_AGENT ^Net\ Vampire [OR]
RewriteCond %HTTP_USER_AGENT ^NetZIP [OR]
RewriteCond %HTTP_USER_AGENT ^Octopus [OR]
RewriteCond %HTTP_USER_AGENT ^Offline\ Explorer [OR]
RewriteCond %HTTP_USER_AGENT ^Offline\ Navigator [OR]
RewriteCond %HTTP_USER_AGENT ^PageGrabber [OR]
RewriteCond %HTTP_USER_AGENT ^Papa\ Foto [OR]
RewriteCond %HTTP_USER_AGENT ^pavuk [OR]
RewriteCond %HTTP_USER_AGENT ^pcBrowser [OR]
RewriteCond %HTTP_USER_AGENT ^RealDownload [OR]
RewriteCond %HTTP_USER_AGENT ^ReGet [OR]
RewriteCond %HTTP_USER_AGENT ^SiteSnagger [OR]
RewriteCond %HTTP_USER_AGENT ^SmartDownload [OR]
RewriteCond %HTTP_USER_AGENT ^SuperBot [OR]
RewriteCond %HTTP_USER_AGENT ^SuperHTTP [OR]
RewriteCond %HTTP_USER_AGENT ^Surfbot [OR]
RewriteCond %HTTP_USER_AGENT ^tAkeOut [OR]
RewriteCond %HTTP_USER_AGENT ^Teleport\ Pro [OR]
RewriteCond %HTTP_USER_AGENT ^VoidEYE [OR]
RewriteCond %HTTP_USER_AGENT ^Web\ Image\ Collector [OR]
RewriteCond %HTTP_USER_AGENT ^Web\ Sucker [OR]
RewriteCond %HTTP_USER_AGENT ^WebAuto [OR]
RewriteCond %HTTP_USER_AGENT ^WebCopier [OR]
RewriteCond %HTTP_USER_AGENT ^WebFetch [OR]
RewriteCond %HTTP_USER_AGENT ^WebGo\ IS [OR]
RewriteCond %HTTP_USER_AGENT ^WebLeacher [OR]
RewriteCond %HTTP_USER_AGENT ^WebReaper [OR]
RewriteCond %HTTP_USER_AGENT ^WebSauger [OR]
RewriteCond %HTTP_USER_AGENT ^Website\ eXtractor [OR]
RewriteCond %HTTP_USER_AGENT ^Website\ Quester [OR]
RewriteCond %HTTP_USER_AGENT ^WebStripper [OR]
RewriteCond %HTTP_USER_AGENT ^WebWhacker [OR]
RewriteCond %HTTP_USER_AGENT ^WebZIP [OR]
RewriteCond %HTTP_USER_AGENT ^Wget [OR]
RewriteCond %HTTP_USER_AGENT ^Widow [OR]
RewriteCond %HTTP_USER_AGENT ^WWWOFFLE [OR]
RewriteCond %HTTP_USER_AGENT ^Xaldon\ WebSpider [OR]
RewriteCond %HTTP_USER_AGENT ^Zeus
RewriteRule ^.* - [F,L]

 


Prevent viewing of .htaccess file


 


 Prevent viewing of .htaccess file


If you use htaccess for password protection, then the location containing all of your password information is plainly available through the htaccess file. If you have set incorrect permissions or if your server is not as secure as it could be, a browser has the potential to view an htaccess file through a standard web interface and thus compromise your site/server. This, of course, would be a bad thing. However, it is possible to prevent an htaccess file from being viewed in this manner:


<Files .htaccess>
order allow,deny
deny from all
</Files>

 


The first line specifies that the file named .htaccess is having this rule applied to it. You could use this for other purposes as well if you get creative enough.


 


Preventing hot linking of images and other file types


Recently when I did an image search on images in my website, I Found there are some site that are using the same images that i uploaded into my server. That website is directly used images in my server by just calling images from my server. If you are a website owner or a blogger I’m sure that you may also experiences the same problem. The precess of steeling images from a website without any permission of that website owner is called Hotlinking. Now a days it found to be a common practice.


With all the pieces in place, here’s how to disable hot linking of certain file types on your site, in the case below, images, JavaScript (js) and CSS (css) files on your site. Simply add the below code to your .htaccess file, and upload the file either to your root directory, or a particular subdirectory to localize the effect to just one section of your site:


RewriteEngine on
RewriteCond %HTTP_REFERER !^$
RewriteCond %HTTP_REFERER !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|js|css)$ - [F]

 


Be sure to replace “mydomain.com” with your own. The above code creates a failed request when hot linking of the specified file types occurs. In the case of images, a broken image is shown instead.


Serving alternate content when hot linking is detected


You can set up your .htaccess file to actually serve up different content when hot linking occurs. This is more commonly done with images, such as serving up an Angry Man image in place of the hot linked one. The code for this is:


RewriteEngine on
RewriteCond %HTTP_REFERER !^$
RewriteCond %HTTP_REFERER !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/tutorial.gif [R,L]

Same deal- replace mydomain.com with your own, plus tutorial.gif


 


WordPress Preconfigured htaccess


Basic WP


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

 


Multisite



WordPress 3.5 and up


If you activated Multisite on WordPress 3.5 or later, use one of these.


Subfolder Example


RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %REQUEST_FILENAME -f [OR]
RewriteCond %REQUEST_FILENAME -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

 


SubDomain Example


RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %REQUEST_FILENAME -f [OR]
RewriteCond %REQUEST_FILENAME -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

 


 


Joomla Preconfigured htaccess


## Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
# mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %QUERY_STRING mosConfig_[a-zA-Z_]1,21(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %QUERY_STRING base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %QUERY_STRING (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %QUERY_STRING GLOBALS(=|\[|\%[0-9A-Z]0,2) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %QUERY_STRING _REQUEST(=|\[|\%[0-9A-Z]0,2)
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_URI !^/index.php
RewriteCond %REQUEST_URI (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$ [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%HTTP:Authorization,L]
#

 Drupal htaccess


#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Tag|Template|all-wcprops|entries|format)$">
Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Force simple error message for requests for non-existent favicon.ico.
<Files favicon.ico>
# There is no end quote below, for compatibility with Apache 1.3.
ErrorDocument 404 "The requested file favicon.ico was not found.
</Files>

# Set the default handler.
DirectoryIndex index.php

# Override PHP settings. More in sites/default/settings.php
# but the following cannot be changed at runtime.

# PHP 4, Apache 1.
<IfModule mod_php4.c>
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
</IfModule>

# PHP 4, Apache 2.
<IfModule sapi_apache2.c>
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
</IfModule>

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On

# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600

<FilesMatch \.php$>
# Do not allow PHP scripts to be cached unless they explicitly send cache
# headers themselves. Otherwise all scripts would have to overwrite the
# headers set by mod_expires if they want another caching behavior. This may
# fail if an error occurs early in the bootstrap process, and it may cause
# problems if a non-Drupal PHP file is installed in a subdirectory.
ExpiresActive Off
</FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# adapt and uncomment the following:
# RewriteCond %HTTP_HOST ^example\.com$ [NC]
# RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment and adapt the following:
# RewriteCond %HTTP_HOST ^www\.example\.com$ [NC]
# RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal
#
# If your site is running in a VirtualDocumentRoot at http://example.com/,
# uncomment the following line:
# RewriteBase /

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_URI !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</IfModule>

# $Id: .htaccess,v 1.90.2.5 2010/02/02 07:25:22 dries Exp $

 



Ultimate Guide and tutorial for .htaccess Files

Sunday, March 16, 2014

CSS Glowing form field on focus

form-glow


 


Now a days most of the modern  website form field using glowing effect  like twitter.com Form fields will glow when you focus on it. This can be done using CSS3 box-shadow and transition property.


 


Step 1: Prepare HTML

Make a HTML form in your html page.


<form class="form">
<label>Name:</label> <input type="text" />
<label>Email:</label> <input type="email" />
<label>Password:</label> <input type="password" />
<input type="button" value="submit" />
</form>

 


Step 2: Prepare CSS

Add CSS code into stylesheet for form input fields.


.form input
border: 1px solid #ddd;
outline: none;
border-radius: 4px;
-webkit-transition: all 0.30s ease-in-out;
-moz-transition: all 0.30s ease-in-out;
-ms-transition: all 0.30s ease-in-out;
-o-transition: all 0.30s ease-in-out;
transition: all 0.30s ease-in-out;


.form input:focus
border-color: #83b4db;
box-shadow: 0 0 10px #8fbfe6;
-moz-box-shadow: 0 0 10px #8fbfe6;
-webkit-box-shadow: 0 0 10px #8fbfe6;

 


You have Done!!!


DEMO



CSS Glowing form field on focus

Saturday, March 15, 2014

Log Viewer for Laravel 4

Easily view and delete Laravel 4′s logs.


Installation


Add kmd/logviewer as a requirement to composer.json:



...
"require":
...
"kmd/logviewer": "1.1.*"
...
,

 


Update composer:


$ php composer.phar update

 


Add the provider to your app/config/app.php:


'providers' => array(

...
'Kmd\Logviewer\LogviewerServiceProvider',

),

 


Publish package assets:


$ php artisan asset:publish kmd/logviewer

 


(Optional) You can configure your composer.json to do this after each $ composer update:


"scripts":
"post-update-cmd":[
"php artisan asset:publish kmd/logviewer",
"php artisan optimize",
]
,

 


(Optional) Publish package config:


$ php artisan config:publish kmd/logviewer

 


Please note: if you have made changes in your app/config/packages/kmd/logviewer/config.php, DO NOT publish the package config again. It will overwrite yours without any warning.


Usage and Configuration


Usage


By default, LogViewer will register itself a couple of routes:


LogViewer also registers a couple filters:


  • logviewer.logs: aggregates all the logs in your configured monitored directories and shares them with the$logs variable.

  • logviewer.messages: Checks if there are success, error, or info flash messages in the session and sets the $has_messages variable as true or false.

Configuration


  • base_url: The URL LogViewer will be available on. You can have this nested (for example: admin/logviewer). Default: logviewer.

  • filters: Before and After filters to apply to the routes. We define no filters by default, as not everyone uses authentication or the same filter names.
    • global: Filters that affect the entirety of the logviewer. For example: 'global' => array('before' => 'auth'), will apply the default Laravel auth filter to the logviewer, requiring a logged in user for all routes.

    • view: Filters that affect the viewing of log files.

    • delete: Filter that affect the deletion of log files.


  • log_dirs: Associative array of log directories to monitor. Array keys are the ‘names’ of your applications, values are the paths to their app/storage/logs dir (no trailing slash). Default: array('app' => storage_path().'/logs').

  • log_order: Order log contents ascending or descending. Default: ‘asc’.

  • per_page: The number of log messages to show per page via Pagination. Default: 10.

  • view: The name (and location) of the view used to display logs. For more information, check out the ‘Advanced Usage’ section for detailed information about the variables passed to this view. Default: ‘logviewer::viewer’.

  • p_view: The pagination view to use. When using Bootstrap 3 as the default for an application, the pagination would be broken within LogViewer. If you create your own view, be sure to change this if you use Bootstrap 3 (or write your own pagination view) Default: ‘pagination::slider’.

Advanced Usage


Don’t like the way LogViewer looks? Need to integrate it better with your application’s theme? You can do so by creating your own view and changing the configuration option. Here are the variables that are sent to the view:


  • $has_messages: Boolean. The logviewer.messages filter determines if there are success, error, or info flash messages in the session. Used to hide the flash messages container.

  • $logs: Array. Aggregated logs, generated by the logviewer.logs filter, from all monitored applications. Grouped by SAPI and application. Structure:
    • SAPI as key, value is an array with keys:
      • sapi: Human-readable SAPI.

      • logs: Application ‘short name’ as key, value is an array of log dates.



  • $log: Array. Currently selected log’s contents. Each message is split into an array. Structure:
    • level: String. The level of the log message.

    • header: String. The first line of the log message.

    • stack: String. The rest of the log message. Possibly blank, if the message did not contain a stack trace.


  • $empty: Boolean. Whether the current log is empty or not.

  • $date: String. The date of the currently selected log.

  • $sapi: String. The human-readable SAPI of the currently selected log.

  • $sapi_plain: String. The SAPI of the currently selected log. Used in the URI.

  • $url: String. The base URL from configuration.

  • $levels: Array. All possible log levels, per psr/log.

  • $path: String. The array key of the currently selected log’s application.

Demo / Download Log Viewer for Laravel 4 



Log Viewer for Laravel 4

Friday, March 14, 2014

How to make jQuery Image caption Overlay

caption-slider


 


In this jQuery  tutorial we will create caption overlay slider using jQuery. This is very useful to show some description of any image on hover affect. This saves space and also looks very attractive in your website.


Step 1: Prepare HTML


Create HTML code for the overlay caption in your html page.
Note: Place an image named 1.jpg in /images folder.


<div class="box">
<div class="caption">
<h3>This is Image One</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla commodo dolor in dui lacinia gravida.</p>
</div>
<img src="images/1.jpg" />
</div>

 


Step 2: Add CSS


Add CSS properties for box and caption in your stylesheet.


.box 
position: relative;
float: left;
width: 300px;
height: 300px;


.caption
display: none;
position: absolute;
background: #000;
opacity: 0.7;
top: 0;
left: 0;
width: 90%;
height: 90%;
padding: 5%;
color: #fff;

 


Step 3: Call jQuery Library from google CDN (if your site already have dont use second time)


Call jQuery library in your webpage. I am using Google CDN hosted jQuery library. (if your site already have dont use second time)


 


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

 


Step 4: Add jQuery code


you can use this into your body  after your html code


<script type="text/javascript">
$(document).ready(function()
$('.box').hover(function()
$(this).find('.caption').slideDown();
,
function()
$(this).find('.caption').slideUp();

);
);
</script>

 


You Have  Done!!!



How to make jQuery Image caption Overlay

Admin Panel for Laravel 4

Laravel 4 package used to provide an admin panel with user, groups and permissions management.


Features


  • Cartalyst Sentry package

  • Anahkiasen Former package

  • Twitter Bootstrap 2.3.1

  • Font-awesome 3.2.0

  • Users, Groups and Permissions out of the box.

  • Base controller for admin panel development

  • Most of the views can be replaced by your own in the config file

Installation


Begin by installing this package through Composer. Edit your project’s composer.json file to require stevemo/cpanel.



"require":
"stevemo/cpanel": "dev-develop"


 


Update your packages with composer update or install with composer install.


You need to add the following service provider. Open app/config/app.php, and add a new items to the providers array.


Former\FormerServiceProvider
Cartalyst\Sentry\SentryServiceProvider
Stevemo\Cpanel\CpanelServiceProvider

 


Then add the following Class Aliases


'Former' => 'Former\Facades\Former',
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',

 


Finally run the following command in the terminal. php artisan cpanel:install This will publish the config files for Cartalyst/Sentry, Anahkiasen/Former and Stevemo/Cpanel also it will run the migration.


To create a user simply do php artisan cpanel:user


Done! Just go to http://localhost/admin to access the admin panel.


Download Admin Panel for Laravel 4



Admin Panel for Laravel 4

Admin package for Laravel 4

Syntara is an admin system for Laravel 4, made for user management easier


user_list


 


Features


  • Authentication

  • Users management

  • Groups & permissions management

  • Responsive design

  • i18n support :
    • English (en)

    • French (fr)

    • Italian (it)

    • Romanian (ro)

    • Russian (ru)

    • Slovenian (sl)

    • Vietnamese (vi)

    • Spanish (es)

    • Swedish (se)

    • Greek (el)

    • Turkish (tr)

    • Dutch (nl)

    • Uyghur (ug)


  • RTL languages support

 


INSTALLATION


You need to have an installed Laravel 4, if not : please read the L4 install doc


Config providers & alias


In app/config/app.php


Add 'Cartalyst\Sentry\SentryServiceProvider' 
and 'Mrjuliuss\Syntara\SyntaraServiceProvider' to the end of the$providers array

 Add 'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry' to the end of the $aliases array

'providers' => array(
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
...
'Cartalyst\Sentry\SentryServiceProvider',
'Mrjuliuss\Syntara\SyntaraServiceProvider'
),
Add 'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry' to the end of the $aliases array
'aliases' => array(

'App' => 'Illuminate\Support\Facades\App',
'Artisan' => 'Illuminate\Support\Facades\Artisan',
...
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry'
),

Before the next step, don’t forget to configure your database inapp/config/database.php Please note that syntara is not compatible with sqlite.


Install command


php artisan syntara:install


Create first user


The first user must add to the “Admin” group, to allow you an access to all features


php artisan create:user username email password Admin


Now you can access to the login page : http://your-url/dashboard/login



Admin package for Laravel 4

Wednesday, March 12, 2014

Theme and asset managing for laravel 4

Theme management for Laravel version 4, it is the easiest way to organize your skins, layouts and assets to your laravel 4 website.


Right now Theme supports PHP, Blade, and Twig.


Create theme with artisan CLI


The first time you have to create theme “default” structure, using the artisan command:


php artisan theme:create default

If you change the facade name you can add an option –facade=”Alias”.


To remove an existing theme, use the command:


php artisan theme:destroy default

the type can be php, blade and twig.


Create from the applicaton without CLI.


Artisan::call('theme:create', array('name' => 'foo', '--type' => 'blade'));

 


Configuration


After the config is published, you will see the config file in “app/config/packages/teepluss/theme” location , but all the configuration can be replaced by a config file inside a theme.


Theme config location: /public/themes/[theme]/config.php


The config is convenient for setting up basic CSS/JS, partial composer, breadcrumb template and also metas.


Example:


'events' => array(

// Before event inherit from package config and the theme that call before,
// you can use this event to set meta, breadcrumb template or anything
// you want inheriting.
'before' => function($theme)

// You can remove this line anytime.
$theme->setTitle('Copyright © 2013 - Laravel.in.th');

// Breadcrumb template.
// $theme->breadcrumb()->setTemplate('
// <ul>
// @foreach ($crumbs as $i => $crumb)
// @if ($i != (count($crumbs) - 1))
// <li><a href=" $crumb["url"] "> $crumb["label"] </a><span>/</span></li>
// @else
// <li> $crumb["label"] </li>
// @endif
// @endforeach
// </ul>
// ');
,

// Listen on event before render a theme,
// this event should call to assign some assets,
// breadcrumb template.
'beforeRenderTheme' => function($theme)

// You may use this event to set up your assets.
// $theme->asset()->usePath()->add('core', 'core.js');
// $theme->asset()->add('jquery', 'vendor/jquery/jquery.min.js');
// $theme->asset()->add('jquery-ui', 'vendor/jqueryui/jquery-ui.min.js', array('jquery'));

// $theme->partialComposer('header', function($view)
//
// $view->with('auth', Auth::user());
// );
,

// Listen on event before render a layout,
// this should call to assign style, script for a layout.
'beforeRenderLayout' => array(

'default' => function($theme)

// $theme->asset()->usePath()->add('ipad', 'css/layouts/ipad.css');


)

)

 


Basic usage


class HomeController extends BaseController 

public function getIndex()

$theme = Theme::uses('default')->layout('mobile');

$view = array(
'name' => 'Teepluss'
);

// home.index will look up the path 'app/views/home/index.php'
return $theme->of('home.index', $view)->render();

// Specific status code with render.
// return $theme->of('home.index', $view)->render(200);

// home.index will look up the path 'app/views/mobile/home/index.php'
$theme->ofWithLayout('home.index', $view)->render();

// home.index will look up the path 'public/themes/default/views/home/index.php'
// return $theme->scope('home.index', $view)->render();

// home.index will look up the path 'public/themes/default/views/mobile/home/index.php'
$theme->scopeWithLayout('home.index', $view)->render();

// Looking for a custom path.
// return $theme->load('app.somewhere.viewfile', $view)->render();

// Working with cookie
// $cookie = Cookie::make('name', 'Tee');
// return $theme->of('home.index', $view)->withCookie($cookie)->render();



 


Get only content “$theme->of(‘home.index’)->content();”.


Searching from both theme’s view and application’s view.


$theme = Theme::uses('default')->layout('default');

return $theme->watch('home.index')->render();

 


To check whether your theme exists.


// Returns boolean.
Theme::exists('themename');

 


To find the location of a view.


$which = $theme->scope('home.index')->location();

echo $which; // themer::views.home.index

$which = $theme->scope('home.index')->location(true);

echo $which; // ./app/public/themes/name/views/home/index.blade.php

 


Compiler


This Theme now supports PHP, Blade and Twig. To use Blade or Twig template you just create a file with extension


[file].blade.php or [file].twig.php

 


Render from string.


// Blade template.
return $theme->string('<h1> $name </h1>', array('name' => 'Teepluss'), 'blade')->render();

// Twig Template
return $theme->string('<h1> name </h1>', array('name' => 'Teepluss'), 'twig')->render();

 


 


Compile string


// Blade compile.
$template = '<h1>Name: $name </h1><p> Theme::widget("WidgetIntro", array("userId" => 9999, "title" => "Demo Widget"))->render() </p>';

echo Theme::blader($template, array('name' => 'Teepluss'));

// Twig compile.
$template = '<h1>Name: name </h1><p> Theme.widget("WidgetIntro", "userId" : 9999, "title" : "Demo Widget").render() </p>';

echo Theme::twigy($template, array('name' => 'Teepluss'));

 


Symlink from another view


This is a nice feature when you have multiple files that have the same name, but need to be set as a separate one.


// Theme A : /public/themes/a/views/welcome.blade.php

// Theme B : /public/themes/b/views/welcome.blade.php

// File welcome.blade.php at Theme B is the same as Theme A, so you can do link below:

// ................

// Location: public/themes/b/views/welcome.blade.php
Theme::symlink('a');

// That's it!

 


Basic usage of assets


Add Theme assets in your route.


// path: public/css/style.css
$theme->asset()->add('core-style', 'css/style.css');

// path: public/js/script.css
$theme->asset()->container('footer')->add('core-script', 'js/script.js');

// path: public/themes/[current theme]/assets/css/custom.css
// This case has dependency with "core-style".
$theme->asset()->usePath()->add('custom', 'css/custom.css', array('core-style'));

// path: public/themes/[current theme]/assets/js/custom.js
// This case has dependency with "core-script".
$theme->asset()->container('footer')->usePath()->add('custom', 'js/custom.js', array('core-script'));

You can force use theme to look up existing theme by passing parameter to method: $theme->asset()->usePath(‘default’)


Writing in-line style or script.


// Dependency with.
$dependencies = array();

// Writing an in-line script.
$theme->asset()->writeScript('inline-script', '
$(function()
console.log("Running");
)
', $dependencies);

// Writing an in-line style.
$theme->asset()->writeStyle('inline-style', '
h1 font-size: 0.9em;
', $dependencies);

// Writing an in-line script, style without tag wrapper.
$theme->asset()->writeContent('custom-inline-script', '
<script>
$(function()
console.log("Running");
);
</script>
', $dependencies);

 


Render styles and scripts in your layout.


// Without container
echo Theme::asset()->styles();

// With "footer" container
echo Theme::asset()->container('footer')->scripts();

 


Direct path to theme asset.


echo Theme::asset()->url('img/image.png');

 


Preparing group of assets.


Some assets you  dont need to add on a page right now, but you still need them sometimes, so “cook” and “serve” is your magic.


Cook your assets.


Theme::asset()->cook('backbone', function($asset)

$asset->add('backbone', '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js');
$asset->add('underscorejs', '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js');
);

 


You can prepare on a global in package config.


// Location: app/config/packages/teepluss/theme/config.php
....
'events' => array(

....

// This event will fire as a global you can add any assets you want here.
'asset' => function($asset)

// Preparing asset you need to serve after.
$asset->cook('backbone', function($asset)

$asset->add('backbone', '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js');
$asset->add('underscorejs', '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js');
);


)
....

 


Serve theme when you need.


// At the controller.
Theme::asset()->serve('backbone');

 


Then you can get output.


...
<head>
<?php echo Theme::asset()->scripts(); ?>
<?php echo Theme::asset()->styles(); ?>
<?php echo Theme::asset()->container('YOUR_CONTAINER')->scripts(); ?>
<?php echo Theme::asset()->container('YOUR_CONTAINER')->styles(); ?>
</head>
...

 


Asset compression


Theme asset has the feature to compress assets by using queue.


// To queue asset outside theme path.
$theme->asset()->queue('queue-name')->add('one', 'js/one.js');
$theme->asset()->queue('queue-name')->add('two', 'js/two.js');

// To queue asset inside theme path.
$theme->asset()->queue('queue-name')->usePath()->add('xone', 'js/one.js');
$theme->asset()->queue('queue-name')->usePath()->add('xtwo', 'js/two.js');

// You can group all assets in a one queue also.
$theme->asset()->queue('queue-name', function($asset)

$theme->asset()->queue('queue-name')->add('one', 'js/one.js');
$theme->asset()->queue('queue-name')->usePath()->add('xtwo', 'js/two.js');
);

 


To render compressed assets inside view.


echo Theme::asset()->queue('queue-name')->scripts(array('defer' => 'defer'));
echo Theme::asset()->queue('queue-name')->styles(array('async' => 'async'));

 


To force compress.


$theme->asset()->queue('queue-name')->compress();

 


When you need best performance on production, you can stop compress using “capture”.


echo Theme::asset()->queue('queue-name')->capture()->scripts();
echo Theme::asset()->queue('queue-name')->capture()->styles();

// Trick !

echo Theme::asset()->queue('queue-name')->capture(App::environmenet() == 'production')->scripts();

// This will stop any process of compression.

 


If you have already published the config before this feature was available, you need to re-publish the config.


Partials


Render a partial in your layouts or views.


// This will look up to "public/themes/[theme]/partials/header.php"
echo Theme::partial('header', array('title' => 'Header'));

 


Partial composer.


$theme->partialComposer('header', function($view)

$view->with('key', 'value');
);

 


Working with regions.


Theme has magic methods to set, prepend and append anything.


$theme->setTitle('Your title');

$theme->appendTitle('Your appended title');

$theme->prependTitle('Hello: ....');

$theme->setAnything('anything');

$theme->setFoo('foo');

// or

$theme->set('foo', 'foo');

 


Render in your layout or view.


Theme::getAnything();

Theme::getFoo();

// or use place.

Theme::place('anything');

Theme::place('foo', 'default-value-if-it-does-not-exist');

// or

Theme::get('foo');

 


Check if the place exists or not.


<?php if (Theme::has('title')) : ?>
<?php echo Theme::place('title'); ?>
<?php endif; ?>

// or

<?php if (Theme::hasTitle()) : ?>
<?php echo Theme::getTitle(); ?>
<?php endif; ?>

 


Get argument assigned to content in layout or region.


Theme::getContentArguments();

// or

Theme::getContentArgument('name');

// To check if it exists

Theme::hasContentArgument('name');

 


Theme::place(‘content’) is a reserve region to render sub-view.


Preparing data to view


Sometimes you don’t need to execute heavy processing, so you can prepare and use when you need it.


$theme->bind('something', function()

return 'This is bound parameter.';
);

 


Using bound data on view.


echo Theme::bind('something');

 


Breadcrumb


In order to use breadcrumbs, follow the instruction below:


$theme->breadcrumb()->add('label', 'http://...')->add('label2', 'http:...');

// or

$theme->breadcrumb()->add(array(
array(
'label' => 'label1',
'url' => 'http://...'
),
array(
'label' => 'label2',
'url' => 'http://...'
)
));

 


To render breadcrumbs.


echo $theme->breadcrumb()->render();

// or

echo Theme::breadcrumb()->render();

 


You can setup breadcrumbs template anywhere you want by using a blade template.


$theme->breadcrumb()->setTemplate('
<ul>
@foreach ($crumbs as $i => $crumb)
@if ($i != (count($crumbs) - 1))
<li><a href=" $crumb["url"] "> $crumb["label"] </a><span>/</span></li>
@else
<li> $crumb["label"] </li>
@endif
@endforeach
</ul>
');

 


Theme Widgets Design Structure


Theme has many useful features to use in your site called “widget” that can be anything.


Creating a widget


You can create a widget class using artisan command:


Creating as a global.


php artisan theme:widget demo --global --type=blade --case=snake

 


Widget tpl is located in /app/views/widgets/widget-tpl.extension


Creating a specific theme name.


php artisan theme:widget demo default --type=blade

 


Widget tpl is located in /public/themes/[theme]/widgets/widget-tpl.extension


The file name can be demo.php, demo.blade.php or demo.twig.php


Now you will see a widget class at /app/widgets/WidgetDemo.php


<h1>User Id: $label </h1>

 


Calling your widget in layout or view


echo Theme::widget('demo', array('label' => 'Demo Widget'))->render();

 


Using theme global


class BaseController extends Controller 

/**
* Theme instance.
*
* @var \Teepluss\Theme\Theme
*/
protected $theme;

/**
* Construct
*
* @return void
*/
public function __construct()

// Using theme as a global.
$this->theme = Theme::uses('default')->layout('ipad');



 


To override theme or layout.


public function getIndex()

$this->theme->uses('newone');

// or just override layout
$this->theme->layout('desktop');

$this->theme->of('somewhere.index')->render();

 



Theme and asset managing for laravel 4

Tuesday, March 11, 2014

shopping cart for Laravel 4

A simple shopping cart implementation for Laravel 4


The shoppingcart gives you the following methods to use:


Cart::add()


/**
* Add a row to the cart
*
* @param string|Array $id Unique ID of the item|Item formated as array|Array of items
* @param string $name Name of the item
* @param int $qty Item qty to add to the cart
* @param float $price Price of one item
* @param Array $options Array of additional options, such as 'size' or 'color'
*/

// Basic form
Cart::add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));

// Array form
Cart::add(array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'options' => array('size' => 'large')));

// Batch method
Cart::add(array(
array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00),
array('id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'options' => array('size' => 'large'))
));

 


Cart::update()


/**
* Update the quantity of one row of the cart
*
* @param string $rowId The rowid of the item you want to update
* @param integer|Array $attribute New quantity of the item|Array of attributes to update
* @return boolean
*/
$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::update($rowId, 2);

OR

Cart::update($rowId, array('name' => 'Product 1'));

 


Cart::remove()


/**
* Remove a row from the cart
*
* @param string $rowId The rowid of the item
* @return boolean
*/

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::remove($rowId);

 


Cart::get()


/**
* Get a row of the cart by its ID
*
* @param string $rowId The ID of the row to fetch
* @return CartRowCollection
*/

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::get($rowId);

 


Cart::content()


/**
* Get the cart content
*
* @return CartCollection
*/

Cart::content();

 


Cart::destroy()


/**
* Empty the cart
*
* @return boolean
*/

Cart::destroy();

 


Cart::total()


/**
* Get the price total
*
* @return float
*/

Cart::total();

 


Cart::count()


/**
* Get the number of items in the cart
*
* @param boolean $totalItems Get all the items (when false, will return the number of rows)
* @return int
*/

Cart::count(); // Total items
Cart::count(false); // Total rows

 


Cart::search()


/**
* Search if the cart has a item
*
* @param Array $search An array with the item ID and optional options
* @return Array|boolean
*/

Cart::search(array('id' => 1, 'options' => array('size' => 'L'))); // Returns an array of rowid(s) of found ite

 


Collections


As you might have seen, the Cart::content() and Cart::get() methods both return a Collection, a CartCollection and a CartRowCollection.


These Collections extends the ‘native’ Laravel 4 Collection class, so all methods you know from this class can also be used on your shopping cart. With some addition to easily work with your carts content.


Instances


Now the packages also supports multiple instances of the cart. The way this works is like this:


You can set the current instance of the cart with Cart::instance('newInstance'), at that moment, the active instance of the cart is newInstance, so when you add, remove or get the content of the cart, you work with the newInstance instance of the cart. If you want to switch instances, you just call Cart::instance('otherInstance') again, and you’re working with the otherInstance again.


So a little example:



Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99);

// Get the content of the 'shopping' cart
Cart::content();

Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, array('size' => 'medium'));

// Get the content of the 'wishlist' cart
Cart::content();

// If you want to get the content of the 'shopping' cart again...
Cart::instance('shopping')->content();

// And the count of the 'wishlist' cart again
Cart::instance('wishlist')->count();



N.B. Keep in mind that the cart stays in the last set instance for as long as you don’t set a different one during script execution.


N.B.2 The default cart instance is called main, so when you’re not using instances,Cart::content(); is the same as Cart::instance('main')->content().



Models


A new feature is associating a model with the items in the cart. Let’s say you have a Product model in your application. With the new associate() method, you can tell the cart that an item in the cart, is associated to the Product model.


That way you can access your model right from the CartRowCollection!


Here is an example:


<?php 

/**
* Let say we have a Product model that has a name and description.
*/

Cart::associate('Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));

$content = Cart::content();

foreach($content as $row)

echo 'You have ' . $row->qty . ' items of ' . $row->product->name . ' with description: "' . $row->product->description . '" in your cart.';

 


The key to access the model is the same as the model name you associated (lowercase). The associate()method has a second optional parameter for specifying the model namespace.


Exceptions


The Cart package will throw exceptions if something goes wrong. This way it’s easier to debug your code using the Cart package or to handle the error based on the type of exceptions. The Cart packages can throw the following exceptions:
















ExceptionReason
ShoppingcartInstanceExceptionWhen no instance is passed to the instance() method
ShoppingcartInvalidItemExceptionWhen a new product misses one of it’s arguments (idname,qtyprice)
ShoppingcartInvalidPriceExceptionWhen a non-numeric price is passed
ShoppingcartInvalidQtyExceptionWhen a non-numeric quantity is passed
ShoppingcartInvalidRowIDExceptionWhen the $rowId that got passed doesn’t exists in the current cart
ShoppingcartUnknownModelExceptionWhen an unknown model is associated to a cart row

Events


The cart also has events build in. There are five events available for you to listen for.














EventFired
cart.add($item)When a single item is added
cart.batch($items)When a batch of items is added
cart.update($rowId)When an item in the cart is updated
cart.remove($rowId)When an item is removed from the cart
cart.destroy()When the cart is destroyed

Example


Below is a little example of how to list the cart content in a table:


// Controller

Cart::add('192ao12', 'Product 1', 1, 9.99);
Cart::add('1239ad0', 'Product 2', 2, 5.95, array('size' => 'large'));

// View

<table>
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Item Price</th>
<th>Subtotal</th>
</tr>
</thead>

<tbody>

<?php foreach($cart as $row) :?>

<tr>
<td>
<p><strong><?php echo $row->name;?></strong></p>
<p><?php echo ($row->options->has('size') ? $row->options->size : '');?></p>
</td>
<td><input type="text" value="<?php echo $row->qty;?>"></td>
<td>$<?php echo $row->price;?></td>
<td>$<?php echo $row->subtotal;?></td>
</tr>

<?php endforeach;?>

</tbody>
</table>

 DownloAd shopping cart for Laravel 4



shopping cart for Laravel 4

Backup and restore database support for Laravel 4 applications

Configuration


You can configure the package by adding a backup section in your app/config/database.php.


All settings are optional and have default values.


 // ...

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Backup settings
|--------------------------------------------------------------------------
|
*/
'backup' => array(
// add a backup folder in the app/database/ or your dump folder
'path' => app_path().'/database/backup/',
// add the path to the restore and backup command of mysql
// this exemple is if your are using MAMP server on a mac
'mysql' => array(
'dump_command_path' => '/Applications/MAMP/Library/bin/',
'restore_command_path' => '/Applications/MAMP/Library/bin/',
),
// s3 settings
's3' => array(
'path' => 'your/s3/dump/folder'
)
),

// ...

 


Dependencies


…for MySQL


You need to have mysqldump installed. It’s usually already installed with MySQL itself.


 


Download Backup and restore database support for Laravel 4 applications



Backup and restore database support for Laravel 4 applications

Role-based Permissions for Laravel 4

Entrust provides a flexible way to add Role-based Permissions to Laravel4.


Configuration


Set the propertly values to the config/auth.php. These values will be used by entrust to refer to the correct user table and model.


Concepts


Let’s start by creating the following Roles and Permissions:


$owner = new Role;
$owner->name = 'Owner';
$owner->save();

$admin = new Role;
$admin->name = 'Admin';
$admin->save();

 


Next, with both roles created let’s assign then to the users. Thanks to the HasRole trait this are gonna be easy as:


$user = User::where('username','=','Zizaco')->first();

/* role attach alias */
$user->attachRole( $admin ); // Parameter can be an Role object, array or id.

/* OR the eloquent's original: */
$user->roles()->attach( $admin->id ); // id only
Now we just need to add permissions to those Roles.

$managePosts = new Permission;
$managePosts->name = 'manage_posts';
$managePosts->display_name = 'Manage Posts';
$managePosts->save();

$manageUsers = new Permission;
$manageUsers->name = 'manage_users';
$manageUsers->display_name = 'Manage Users';
$manageUsers->save();

$owner->perms()->sync(array($managePosts->id,$manageUsers->id));
$admin->perms()->sync(array($managePosts->id));

 


Now we can check for roles and permissions simply by doing:


$user->hasRole("Owner"); // false
$user->hasRole("Admin"); // true
$user->can("manage_posts"); // true
$user->can("manage_users"); // false

 


You can have as many Roles was you want in each User and vice versa.


More advanced checking can be done using the awesome ability function. It takes in three parameters (roles, permissions, options). roles is a set of roles to check. permissions is a set of permissions to check. Either of the roles or permissions variable can be a comma separated string or array.


$user->ability(array('Admin','Owner'), array('manage_posts','manage_users'));
//or
$user->ability('Admin,Owner', 'manage_posts,manage_users');

 


This will check whether the user has any of the provided roles and permissions. In this case it will return true since the user is an Admin and has the manage_posts permission.


The third parameter is an options array.


$options = array(
'validate_all' => true | false (Default: false),
'return_type' => boolean | array | both (Default: boolean)
);

 


validate_all is a boolean flag to set whether to check all the values for true, or to return true if at least one role or permission is matched.


return_type specifies whether to return a boolean, array of checked values, or both in an array.


Here’s an example output.


$options = array(
'validate_all' => true,
'return_type' => 'both'
);
list($validate,$allValidations) = $user->ability(array('Admin','Owner'), array('manage_posts','manage_users'), $options);

// Output
var_dump($validate);
bool(false)
var_dump($allValidations);
array(4)
['role']=>
bool(true)
['role_2']=>
bool(false)
['manage_posts']=>
bool(true)
['manage_users']=>
bool(false)

 


Short syntax Route filter


To filter a route by permission or role you can call the following in your app/filters.php:


// Only users with roles that have the 'manage_posts' permission will
// be able to access any route within admin/post.
Entrust::routeNeedsPermission( 'admin/post*', 'manage_posts' );

// Only owners will have access to routes within admin/advanced
Entrust::routeNeedsRole( 'admin/advanced*', 'Owner' );

// Optionally the second parameter can be an array of permissions or roles.
// User would need to match all roles or permissions for that route.
Entrust::routeNeedsPermission( 'admin/post*', array('manage_posts','manage_comments') );

Entrust::routeNeedsRole( 'admin/advanced*', array('Owner','Writer') );

 


Both of these methods accepts a third parameter. If the third parameter is null then the return of a prohibited access will be App::abort(403). Otherwise the third parameter will be returned. So you can use it like:


Entrust::routeNeedsRole( 'admin/advanced*', 'Owner', Redirect::to('/home') );

 


Further both of these methods accept a fourth parameter. It defaults to true and checks all roles/permissions given. If you set it to false, the function will only fail if all roles/permissions fail for that user. Useful for admin applications where you want to allow access for multiple groups.


// If a user has `manage_posts`, `manage_comments` or both they will have access.
Entrust::routeNeedsPermission( 'admin/post*', array('manage_posts','manage_comments'), null, false );

// If a user is a member of `Owner`, `Writer` or both they will have access.
Entrust::routeNeedsRole( 'admin/advanced*', array('Owner','Writer'), null, false );

// If a user is a member of `Owner`, `Writer` or both, or user has `manage_posts`, `manage_comments` they will have access.
// You can set the 4th parameter to true then user must be member of Role and must has Permission.
Entrust::routeNeedsRoleOrPermission( 'admin/advanced*', array('Owner','Writer'), array('manage_posts','manage_comments'), null, false);

 


Route filter


Entrust roles/permissions can be used in filters by simply using the can and hasRole methods from within the Facade.


Route::filter('manage_posts', function()

if (! Entrust::can('manage_posts') ) // Checks the current user

return Redirect::to('admin');

);

// Only users with roles that have the 'manage_posts' permission will
// be able to access any admin/post route.
Route::when('admin/post*', 'manage_posts');
Using a filter to check for a role:

Route::filter('owner_role', function()

if (! Entrust::hasRole('Owner') ) // Checks the current user

App::abort(404);

);

// Only owners will have access to routes within admin/advanced
Route::when('admin/advanced*', 'owner_role');

 


As you can see Entrust::hasRole() and Entrust::can() checks if the user is logged, and then if he has the role or permission. If the user is not logged the return will also be false.


Troubleshooting


If you encounter an error when doing the migration that looks like:


SQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150) (SQL: alter table `assigned_roles` add constraint assigned_roles_user_id_foreign foreign key (`
user_id`) references `users` (`id`)) (Bindings: array (
))

 


Then it’s likely that the id column in your user table does not match the user_id column in assigned_roles. Match sure both are INT(10).


Name is having issues saving.


EntrustRole->name has a length limitation set within the rules variable of the EntrustRole class.


You can adjust it by changing your Role Model.


<?php

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
between:4,255'
);

 


 



Role-based Permissions for Laravel 4

Language for Laravel

you can find the lang files for the framework PHP, Laravel 4


How add languages in my app ?


Language Installation:


  • Download the zip file from here

  • Copy the folders of languages that you want, in app/lang folder of your application Laravel

Installation by Composer


  • Add “caouecs/laravel4-lang”: “dev-master” in your composer.json in “require” or run composer require caouecs/laravel4-lang

  • Do “composer update”

  • Files of languages are in “vendor/caouecs/laravel4-lang” directory

  • Copy the folders of languages that you want, in app/lang folder of your application Laravel

Language by default in your app


In the file app/config/app.php, change the value of language by the short name of your language.


 



Language for Laravel

Sunday, March 9, 2014

Laravel Webserver Configurations

Webserver configuration files for Laravel 4


This post contains some server configuration files to get Laravel 4 running ‘out-of-the-box’ on a number of web servers which you need.


Currently supported:


  • Apache

  • Nginx

  • LigHTTPd

  • Pagodabox Boxfile with PHP 5.4

Download This File



Laravel Webserver Configurations

Messaging library for CodeIgniter

A small library to help jump start your internal messaging system, for the CodeIgniter framework


This library is intended as a starting off point for building an internal messaging system for your CodeIgniter application. It does NOT include any controllers or views. To use this library:


1) download The File


2) there are 5 files (not including this README):


- mahana.sql — run this sql script in your database. Note that these tables are all InnoDB – Mahana uses transactions


- config/mahana.php — you will need to set up your existing users table information here, following the sample data style


- language/english/mahana_lang.php — all error and success messages can be changed here, or multilingual support can be added


models/mahana_model.php — the database model


libraries/Mahana_messaging — the main library file


3) from your controller, load the library as either:


(Recommended)
$this->load->library('mahana_messaging');
$msg = $this->mahana_messaging->get_message($msg_id, $sender_id);

 


or


$this->load->library('mahana_messaging');
$mahana = new Mahana_messaging();
$msg = $mahana->get_message($msg_id, $sender_id);

 


4) All functions return the array:


$status['err'] 1= error, 0 = no error
$status['code'] a specific code for that return value, found in config/mahana.php
$status['msg'] a configurable message, found in language/english/mahana_lang.php
$status['retval'] (optional) returned array of data

 


5) Features


Messaging library  has a couple of small features you should be aware of:


1) using the config/mahana.php constants USER_TABLE_TABLENAME, USER_TABLE_ID, USER_TABLE_USERNAME you may quickly and easily integrate the messaging library with your exisiting user table


2) all return messages are configurable and can be made multi-lingual


3) return array $status makes for easy conversion to json format for ajax-based systems


4) get_full_thread() and get_all_threads() have a unique parameter – $full_thread. If set to true, a newly added participant to a thread can see all messages dating BEFORE he was added, allowing him to “catch up” on the conversation. Ideal for adding a manager or a new salesperson to a conversation.



Messaging library for CodeIgniter

How to remove index.php from URLs In codeigniter

By default, the index.php file will be included in your URLs:


example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:you ha


in your root folder where you have htaccess file add this code into htaccess file.


RewriteEngine on
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteRule .* index.php/$0 [PT,L]

Then Remove index.php from your URL


example.com/index.php/news/article/my_article to example.com/news/article/my_article

 


In the above htaccess , any HTTP request other than those for index.php, images, and robots.txt is treated as a request for your index.php file.



How to remove index.php from URLs In codeigniter

Thursday, March 6, 2014

administrative interface builder for Laravel

Administrator is an administrative interface builder for Laravel.


With Administrator you can visually manage your Eloquent models and their relations, and also create stand-alone settings pages for storing site data and performing site tasks ;) .



 


For more about  administrative interface builder for Laravel  read 


  • Author: Jan Hartigan

  • Version: 4.10.0


administrative interface builder for Laravel