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 (id, name,qty, price)
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