Customize #can() to show a permissions overlay for pages/sections - laravel-5

At work I maintain a fairly complex Laravel application which is still growing as new features are implemented and improved upon.
We have non-technical administrators in this system who manage other users permissions and sometimes it can be hard to know what permission ends up blocking a user from accessing a certain page or what might give a user too much access. Better descriptions for permissions and the ability to simulate a user to see what they have access to is already something we have done.
In addition to this we would like to toggle overlays for permissions defined in blade templates, we might defines this permissions with
#can('update', $post)
<!-- Menu button to update a $post -->
#endcan
or
#can('manage_user_roles_and_permissions')
<!-- A table with many different functions
for managing user roles + permissions -->
#endcan
Is there a way I can modify the way the #can() works in blade templates so that I can add some javascript to show a popover for where a section starts and ends, like "The permission 'Show Post' is needed for this menu button to show" or "To see the following section a user needs the 'Manage user roles and permissions' permissions". Or even better if I could add a div with a red border around the section.
How can I append additional javascript/html where #can() is used in a blade template to show an overlay.

To solve this issue I need to extend blade, see Extending Blade in the Laravel documentation.
The following is a quick test that I did just to see if this was possible. $value in this case is a string which contains the content of a blade file before being processed. So I can use preg_match_all() to find the #can statements and then append my javascript where needed. I can find the #endcan in the same way but it is harder to know which #endcan belongs to which #can but it should be fairly easy to match from this point on.
<?php
namespace App\Providers;
use Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::extend(function($value)
{
$can_array = array();
preg_match_all('/(\s*)#(can)\(([^\)]*)\)(\s*)/', $value, $matches);
if (count($matches) > 0 && isset($matches[3])) {
foreach ($matches[3] as $match) {
if (!in_array($match, $can_array)) {
$can_array[] = $match;
}
}
}
foreach ($can_array as $ca) {
$value = str_replace("#can(" . $ca . ")", "#can(" . $ca . ") \r\n <!-- My javascript code goes here! -->", $value);
}
// TODO need to figure out a better way to handle this
$value = str_replace("#endcan", "#endcan \r\n <!-- Section ended here -->", $value);
return $value;
});
}
...
My source code now looks like this when viewing it, goal achieved!

Related

Backpack for Laravel: how to add 'delete' per-line button conditionally?

I've a parent model which can have n childs
So I want to show delete button ONLY if it has not children (hasMany relationship must return 0 records).
How can I show 'delete' link in each lines of a table (in the list operation), but ONLY if a condition is valid?
The easiest option I see is to use a custom view for the Delete button, instead of the one in the package. Depending on how wide you want this change to be made:
A. If you want to do that across all CRUDs - it's easy, just publish the view by running:
php artisan backpack:publish crud/buttons/delete
This will place the file in your resources/views/vendor/backpack/crud/buttons, for you to change however you like. Inside the delete button view you have the current entry available as $entry so you can do something like $entry->children()->count() if you want. Be mindful that this will be run ONCE PER LINE so if you show 50 lines in the table for example, you'd need to find a way to optimize this.
B. If you want to do that for just one CRUD (eg. do it for Categories but not for Products), then you can do the same thing (publish the button view), but rename the button to something different like delete_if_no_children.blade.php so that it doesn't get used automatically for all CRUDs. Then use it only inside the controllers you want, inside setupListOperation(), by removing the "stock" delete button and adding yours:
// using the Backpack array syntax
$this->crud->removeButton('delete');
$this->crud->addButton('line', 'delete', 'view', 'crud::buttons.delete_if_no_children', 'end');
// using the Backpack fluent syntax
CRUD::button('delete')->view('crud::buttons.delete_if_no_children');
Use
withCount('children')
Docs: withCount
Additionally you can wrap delete buttons with blade directive
#can('destroy', $model) disabled #endcan
Docs: #can
<?php
namespace App\Policies;
use App\Models\Model;
use App\Models\User;
class ModelPolicy
{
public function update(User $user, Model $model)
{
return $model->children_count === 0;
}
}
Docs: policy
A hasMany relationship will return an empty Collection when there are no associated records. You can then proceed to call isEmpty() on the collection to verify there are no child records (children).
Example in PHP:
$parents = Parent::with('children')->get();
And then in your template you can do:
#foreach($parents as $parent)
#if($parent->children->isEmpty())
<button>Delete</button>
#endif
#endforeach

Download database file attachments by their real names

I can't figure out how to get a database file attachment, to be downloaded with is real file name.
My model have many file attachements (many attachOne) and there is no problem to get link to them with
{{ model.myfile.filename }}
What I want to do is to get those files downloaded with their real file name.
I try to define an ajax event handler in my layout like so :
function onDonwload()
{
$path = post('path');
$name = post('name');
// Storage::exists('uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf'); => OK
// Storage::exists($path); =>OK
$path = storage_path().'/app/'. $path;
return Response::download( $path, $name);
}
and
<button data-request="onDonwload"
data-request-data="path: 'uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf', name: 'my real name">
Download
</button>
No missing file error, but get the browser to freeze with an alert that say "A webpage slow down your browser, what do you want to do?".
Did I miss an important point?
You should add separate page for downloading files, Ajax can not help you to download file ( may be it can but process is little complex and long)
create page with /file-download/:id here you can specify any url wit param :id and give it name file-download you can give any name you like for demo i used this name.
In that Page Html section will be Blank and in Page's code section add this code. here you can also check additional security check like user is logged in or not file is of related user or not. for now i am just checking file is related to particular Modal or not.
function onStart() {
$fileId = $this->param('id');
$file = \System\Models\File::find($fileId);
// for security please check attachment_type == your model with namespace
// only then lat use download file other wise user can download all the files by just passing id
if($file && $file->attachment_type == 'Backend\Models\User') { // here add your relation model name space for comparison
$file->output('attachment');
}
else {
echo "Unauthorised.";
}
exit();
}
Generating links, please replace page name with page you created.
<a href="{{ 'file-download'|page({'id': model.myfile.id}) }}" >{{ model.myfile.filename }}</a>
Now, when you click on link file should be downloaded with its original name, and for invalid file id it should show message Unauthorised..
if any doubts please comment.

Laravel 5 Bind data to var for menu in header.blade.php

What is the best solution for creating a menu.
I have $menudata (dynamic from dbase) and want to pass it to a heade.blade.php to generate top menu.
$menudata = Menu::all();
#foreach($menudata as $value).......
How can i achieve that? What's the best way to do it?
Add below code within the boot method of the AppServiceProvider
View::composer('*', function($view)
{
$view->with('menudata', Menu::all());
});
Here, * means all views will receive $menudata.
Now you can use this like
#foreach ($menudata as $menu).....
If the menu is visible in every page then add the following in any service provider (e.g. in the AppServiceProvider):
public function boot() {
// ...
View::share("menudata",Menu::all());
//...
}
Then you can use the menu data in any view e.g.
#foreach($menudata as $value).......
Laravel-menu provides three rendering methods out of the box. However you can create your own rendering method using the right methods and attributes.
As noted earlier, laravel-menu provides three rendering formats out of the box, asUl(), asOl() and asDiv(). You can read about the details here.
{!! $MyNavBar->asUl() !!}
You can also access the menu object via the menu collection:
{!! Menu::get('MyNavBar')->asUl() !!}

How to create multi language menu in Laravel 5

What is the best way to create a main menu in Laravel 5? And how to show menu items only when an user is logged-in? And What is the best way to make this multi language?
Laravel provides an easy way to check if the user is logged-in by using the facade Auth::check().
if (Auth::check()) {
// The user is logged in...
}
About the translation, you can check here: Localization
The structure is defined like this, as per documentation:
/resources
/lang
/en
messages.php
/es
messages.php
Laravel also provides an easy way to translate phrases using the trans('string.to.translate'), which can be seen here trans().
Inside messages.php (in both lang directories), you must set the translation string. In en/messages.php:
return [
'welcome' => 'Welcome'
];
In es/messages.php:
return [
'welcome' => 'Bienvenido'
];
With these two, you can do the following in you application for example:
// Get the user locale, for the sake of clarity, I'll use a fixed string.
// Make sure is the same as the directory under lang.
App::setLocale('en');
Inside your view:
// Using blade, we check if the user is logged in.
// If he is, we show 'Welcome" in the menu. If the lang is set to
// 'es', then it will show "Bienvenido".
#if (Auth::check())
<ul>
<li> {{ trans('messages.welcome') }} </li>
</ul>
#endif
Try with https://laravel.com/docs/5.1/authentication
For example:
if (Auth::check()) {
return something to view
}

How would I structure this in Zend Framework?

I'm coming from CodeIgniter, and the terminology overlap between it and other MVC frameworks (particularly Zend) is giving me a mental block of some kind.
I want my users to visit http://mysite.com/do/this.
I understand that "do" is the Controller, and "this" is a function (well, method) within that Controller.
My site will have common elements like a header and sidebar; I understand that those go into a Layout, which will be incorporated into the final output.
I want the /do/this page to display three visual blocks of information (I'm deliberately not using the word "modules"). Let's call them BlockA, BlockB, and BlockC. Maybe one is a list of "new events" and another is a list of "new posts" and another is something else. Whatever. The trick is, these blocks of information will also be displayed on other pages of the site - say, http://mysite.com/did/that.
Both the "did" and the "do" Controllers (and the "this" and "that" methods, obviously) would be arranging BlockA, BlockB, and BlockC differently. Each Controller would have different criteria for what went into those blocks, too - one might be current information, while another might be archived information from the past.
I want to ensure that future programmers can easily alter the appearance of BlockA, BlockB, and/or BlockC without having to touch the code that populates their data, or the code which arranges them on each page.
So my general feeling is that BlockA, BlockB, and BlockC need to have their visual layout defined in a View - but that View wouldn't be specifically associated with either the "do" or the "did" Controllers. And the code which populates those blocks - that is, queries information from a database, selects the bits that are to be displayed, and whatnot - shouldn't reside entirely in those Controllers, either.
I started down the path of putting the logic - that is, assembling what will be displayed in each block - into Models. I feel I'm on the right path, there; both the "do" and "did" Controllers can thus summon the block-creation code via Models. But how (and where) do I abstract the visual element of those blocks, in such a way that the visual elements can also be shared by these two Controllers? Do the Models somehow load a View and output HTML to the Controllers (that doesn't feel right)? Or is there a way for the Controllers to run the Model, get the data to display, and then somehow feed it to a common/centralized View?
I know how I'd do this in CodeIgniter. But... what's the correct architecture for this, using Zend Framework? I'm convinced that it's very different than what CodeIgniter would do, and I want to start writing this application with the right architecture in mind.
One small naming thing: /:controller/:action/* => /do/this = this is an action (although also both a function and a method in the controller, action is the proper name)
Your blocks to me sound like "partial views". There are a few ways to approach this problem, and depending on how the views work, or what information they need to know, you adapt your strategy
Rendering Partials
You want to use this method when you have some view code you want to be used by multiple views. There are two different approaches using the view helpers Zend_View_Helper::render or Zend_View_Helper_Partial* The render($phtmlfile) view helper is more efficient, the partial($phtmlfile, $module, $params) view helper clones a new view, unseting all parameters, and setting the ones you pass in. An example of how to use them:
case/list.phtml:
<?php
$this->headTitle($this->title);
// works because our controller set our "cases" property in the view, render
// keeps our variables
echo $this->render("case/_caseListTable.phtml");
case/view.phtml
<?php
$this->headTitle($case->title);
?><!--- some view code showing the case -->
<?php if ($cases = $case->getChildren()): ?>
<h3>Children</h3>
<?php echo $this->partial("case/_caseListTable.phtml", "default", array(
"cases"=>$cases,
)); ?>
<?php endif; ?>
case/_caseListTable.phtml
// table header stuff
<?php foreach ($this->cases as $case): ?>
// table rows
<?php endforeach; ?>
// table footer stuff
Custom View Helpers
Sometimes the controller has no business knowing what information is being displayed in the block, and preparing it for your view would be silly, at this point you want to make your own view helpers. You can easily add them to the global view in application.ini:
resources.view.doctype = "XHTML1_STRICT"
resources.view.helperPath.My_View_Helper = APPLICATION_PATH "/../library/My/View/Helper"
I have a tendency to use this method for things that will require additional information from the model not provided by the controller, or blocks of reusable formatting code for the view. A quick example, from a project that I used: Olympic_View_Helper_Ontap grabs the draught beer list and renders it:
class Olympic_View_Helper_Ontap extends Zend_View_Helper_Abstract {
public function Ontap()
{
$view = $this->view;
$box = Olympic_Db::getInstance()->getTable('box')->getBoxFromName('Draught-Beer');
if ($box) $menu = $box->getMenu(); else $menu = null;
$content = "";
if ($menu)
{
$content = "<h1>".$view->escape($menu->title)."</h1>";
$content .= "<ul>";
foreach($menu->getItems() as $item) {
$content .= "<li>".$view->escape($item->name)."</li>";
}
$content .= "</ul>";
}
return $content;
}
}
Then in my layout:
<?php echo $this->ontap(); ?>
Your View Helpers can also accept arguments (of course), can call other view helpers (including partial). Consider them template functions. I like using them for short tasks that are required a lot, for instance $this->caseLink($case) generates a properly formatted <a href='/case/2' class='case project'>Project</a> tag.

Resources