sleeping-owl / admin Goto Github PK
View Code? Open in Web Editor NEWAdministrative interface builder for Laravel
Home Page: http://sleeping-owl.github.io/
License: MIT License
Administrative interface builder for Laravel
Home Page: http://sleeping-owl.github.io/
License: MIT License
Hi, I've wanted to use a custom controller in the admin panel. It seems that I can only route to the action specified in menu configuration. If I create an url to my controller from the view, I cannot get to the action.
For example :
Admin::menu()->url('claims')->label('Claims')->icon('fa-money')->uses('\Controllers\Dashboard\ClaimController@getIndex');
Then, in my action I render a view. From that view I try to provide a link to another method in that controller:
<a class="btn btn-success btn-sm" href="{{action('\Controllers\Dashboard\ClaimController@getInfo', $claim->id)}}">
First it said that it cannot find the route, so i thought that adding a specific route to my routes.php would do the trick, but it sill ignores that :
Route::group(['prefix' => 'admin', 'before' => 'admin.auth'], function ()
{
Route::controller('claims', '\\Controllers\\Dashboard\\ClaimController');
});
The main question is how to use the routing inside the custom controller. Thx
I'm having another date issue, this time is in the javascript/datatables side, when I try to show the date on my model list it breaks JS code and throw an error to the console, the screenshot shows how the datatable is not being fully loaded and the console error.
I'm using Laravel 4.2 with Admin 1.3.7.
Once again thank you very much.
When I choose multiple tags in form, I several tags in grid and in the db. But when I enter the form again, only the first tag is chosen. So if I save it again, only one tag is left.
Admin::model('\App\Models\Product')
->title('Products')
->columns(function ()
{
Column::string('ordr', 'Order');
Column::string('name', 'Name');
Column::lists('tags.name', 'Tags');
})
->form(function ()
{
FormItem::text('ordr', 'Order');
FormItem::text('name', 'Name');
FormItem::multiSelect('tags', 'Tags')
->list('\App\Models\Tag')
->value('tags.product_id');
});
class Product extends \SleepingOwl\Models\SleepingOwlModel
{
protected $guarded = ['id'];
public function scopeDefaultSort( $query )
{
return $query->orderBy( 'subcategory_id', 'asc' )->orderBy( 'ordr', 'asc' );
}
public function tags()
{
return $this->belongsToMany('App\Models\Tag');
}
public function setTagsAttribute($categories)
{
$this->tags()->detach();
if ( ! $categories) return;
if ( ! $this->exists) $this->save();
$this->tags()->attach($categories);
}
}
Hi.
Today I updated laravel to 5.0.16, and I noticed that the login view dont show language translations correctly, therefore I cannot login because don't recognise the rule.
Thanks
В /vendor/sleeping-owl/admin/src/SleepingOwl/Admin/Controllers/AdminController.php:67
в Controller->beforeFilter() передается замыкание, что в итоге вываливается в ошибку:
php artisan route:list
Fatal error: Call to a member function filter() on a non-object in /vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 111
$this->beforeFilter(function (Route $route, Request $request)
{
if ($model = $route->parameter('model'))
{
$this->modelName = $model;
$this->getModelItem();
$this->modelRepository = App::make('SleepingOwl\Admin\Repositories\Interfaces\ModelRepositoryInterface', [
'modelItem' => $this->modelItem,
'request' => $request
]);
$this->queryState->setPrefix($model);
}
});
Т.к. использую монгу, хотелось бы иметь возможность указывать в конфиге класс модели для авторизации.
https://github.com/sleeping-owl/admin/blob/master/src/SleepingOwl/AdminAuth/AdminAuthManager.php#L28
Будет ли поддержка Laravel 5? Если да, то как скоро?
After doing composer update and installing via editing config/app.php (Aliases and Providers), and then doing: php artisan config:publish sleeping-owl/admin
My entire app gets the following error:
PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /Users/david/Sites/neo.billing/app/admin/User.php on line 9
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'","file":"/Users/david/Sites/neo.billing/app/admin/User.php","line":9}}
php artisan throws this as well -- any idea what's happening?
При использовании команды artisan admin:model
, получаем ошибку Undefined index: smallint
, если колонка в таблице имеет тип smallint
Вариант решения return array_get($type, $lookup, 'text');
I encounter this issue when using the default CRUD screens to create a new entity for the given model. Is this related to compatibility with L5?
Getting a sql error while trying to install the package.
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table administrators
add unique administrators_username_unique(usernam e
))
I'm trying to show custom field as column value inside the items list. I've tried:
Column::string('subcategory.title()', 'Subcategory');
and
Column::string('subcategory.title', 'Subcategory');
and the first one produces empty string, and the second one crashes. Is there any way to show something except basic field value?
This is working fine:
Column::string('subcategory.name', 'Subcategory');
Admin::model('\App\Models\Product')
->title('Products')
->with('subcategory')
->filters(function(){
ModelItem::filter('subcategory_id')->title()->from('\App\Models\Subcategory', 'title');
})
->columnFilter()
->columns(function ()
{
Column::string('subcategory.title()', 'Subcategory')
->append(Column::filter('subcategory_id')->value('subcategory.id'));
Column::string('code', 'Code');
Column::string('name', 'Name');
Column::string('price', 'Price');
})
->form(function ()
{
FormItem::select('subcategory_id', 'Subcategory')->list('\App\Models\Subcategory');
FormItem::text('name', 'Name');
FormItem::text('price', 'Price');
FormItem::textarea('description', 'Description');
});
class Subcategory extends \SleepingOwl\Models\SleepingOwlModel
{
protected $guarded = ['id'];
public function scopeDefaultSort( $query )
{
return $query->orderBy( 'ordr', 'asc' );
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function title()
{
return "{$this->category->name} - {$this->name}";
}
public static function getList()
{
$vals = [];
foreach( Subcategory::orderBy( 'category_id', 'asc' )->with( 'category' )->get() as $item )
$vals[$item->id] = "{$item->category->name} - {$item->name}";
return $vals;
}
}
Error when press button is
BadMethodCallException in Builder.php line 1992:
Call to undefined method Illuminate\Database\Query\Builder::validate()
Are you have solution?
Thanks
There is my code and the result:
https://www.dropbox.com/s/knl274ovm0zs1tm/Screenshot%202015-03-29%2003.35.21.png?dl=0
Arrows look correct (0 has only down, 3 has only up), but row order is wrong.
Admin::model('\App\Models\Category')
->title('Categories')
->columns(function ()
{
Column::string('ordr', 'Order')->sortableDefault();
Column::string('name', 'Name');
})
->form(function ()
{
FormItem::text('ordr', 'Order');
FormItem::text('name', 'Name');
});
class Category extends \SleepingOwl\Models\SleepingOwlModel
implements ModelWithOrderFieldInterface
{
protected $guarded = ['id'];
use ModelWithOrderFieldTrait;
public function getSortField()
{
return 'ordr';
}
public function scopeDefaultSort( $query )
{
return $query->orderBy( 'ordr', 'asc' );
}
}
При использовании FormItem::select()->list([1 => 'Пункт 1', 2 => 'Пункт 2'])
получаем вместо
<select>
<option value="1">Пункт 1</option>
<option value="2">Пункт 2</option>
</select>
вот это:
<label class="radio">
<input type="radio" value="Пункт 1"></input>
Пункт 1
</label>
Хотелось бы, чтобы учитывался ключ массива (чтобы он заносился в value), этого очень не хватает.
При сохранении документа столкнулся с ошибкой, которая раньше не возникала.
'DateTime::__construct(): Failed to parse time string (T6FfUtR1CkKEYOrSAOzzvwcFWIpwyPxXxKDd2AMT) at position 1 (6): Unexpected character' in E:\Webprojects\diets\vendor\nesbot\carbon\src\Carbon\Carbon.php:192
Как выяснилось, она возникла из-за того, что значение _token
определялось, как дата по наличию строке символов 'AM'
.
Ещё, после очистки кук в браузере невозможно заново залогиниться, так как возникает ошибка:
Illuminate \ Session \ TokenMismatchException
Route::filter('csrf', function()
{
if (Session::token() !== Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
Пришлось чистить поле remember_token в бд, чтоб залогиниться заново.
Hi guys, for certain circumstances we cannot update our Laravel app to v. 4.2. Is there a way we can use your admin package with this version ? Thx
Было бы неплохо добавить возможность использовать функционал Intervention Image при загрузке изображения.
Hi!
Today I ran composer update to my proyect with Laravel 5, and I've seen that laravel has been updated to 5.0.6, giving me the error described in the title.
It's because Eloquent\Model::newFromBuilder() add an extra paremeter in this version.I have modified my own code in SleepingOwlModel::newFromBuilder() and by now everything is ok.
Sorry for my English
Hi there,
The sleeping_owl_admin.php file does not work after being published to the 'config' directory.
sd:
Как делать проверку, загружено ли изображение к статье?
Ведь, если изображение не было загружено, то такая запись
$recipe->image->thumbnail('original')
вернёт неправильный путь
string(43) "http://diets.dev/img/cache/original/recipes"
А с помощью $recipe->image я не могу получить название загруженного изображения
object(SleepingOwl\Models\Attributes\Image)#453 (2) { ["directory":protected]=> string(8) "recipes/" ["filename":protected]=> NULL }
Хотелось бы, чтобы если изображение не было загружено, $recipe->image->thumbnail('original') возвращал null.
I am trying to create a custom column using the YesNoColumn.php using BaseColumn extend example.
But I am receiving the following error:
FatalErrorException in YesNoColumn.php line 10:
Cannot redeclare class YesNoColumn
I have used composer to autoload the YesNoColumn.php file (in admin/Custom/ folder)
This is been used in Admin::model
Column::yesNo('is_paid', 'Is_paid')->sortable(false);
and in the bootstrap folder I have added:
Column::register('yesNo', App\Admin\Custom\YesNoColumn::class);
However I have no Idea why I am receiving this error.
Kind Regards
Nick
Is there a way to append a filter on a custom column?
I'm using a custom column to show concat of two model columns (first_name and last_name), and would like a link next to it to jump to another Model based on the id.
I am trying to install using Laravel 4.2
I have added the facades and the service providers, as well as adding the dependency to composer.js
When I run:
php artisan admin:install
The first migration occures, but the second one fails, responding with a
[ErrorException] - mkdir(): Permission Denied
error.
Is there something that I am missing?
Thanks!
Hi, first thank you for this great package I just start playing with it, but it looks very nice.
I'm having a validation problem with some timestamp fields on a model, when I try to save it I always get a validation error saying "The DATE_FIELD is not a valid date."
The site is Spanish so it is using Spanish date format, so in the frontend form I can see the picker and the date are sent back to the server with the format "d/m/Y H:i"
------WebKitFormBoundaryCE36NbwdAdXEa6OP
Content-Disposition: form-data; name="fecha_inicio"
12/02/2015 20:42
------WebKitFormBoundaryCE36NbwdAdXEa6OP
Content-Disposition: form-data; name="fecha_fin"
13/02/2015 20:42
------WebKitFormBoundaryCE36NbwdAdXEa6OP--
The validation result:
I guess the problem is with the built-in validation, the Admin uses Laravel's date validation and it uses strtotime to transform the input, but strtotime is not working with the date format because it confuses the month with the day, so from 13th date is considered invalid.
Is there already a method to deal with date format validation?
I'm using the Laravel 4.2 branch.
Thanks!
Пагинация, как я понял, работает через JS. Она быстрая, это впечатляет.
Но я подозреваю, что уже примерно при 200 записях уже будет тормозить.
Что думаете по этому поводу?
Navigation bar is hidden when window width < 768px and there is no way to expand it.
ModelWithOrderFieldTrait::move()
method causes error field 'sort' not found
:
Instead of
$previousRow = static::sortModel()->whereSort($this->{$this->getSortField()} - $destination)->first();
should be
$previousRow = static::sortModel()->where($this->getSortField(), $this->{$this->getSortField()} - $destination)->first();
in line 40
php 5.5
bootstrap.php
Admin::model(Games::class)->title('Games')->columns(function () {
Column::string('name', 'Name');
})->form(function () {
FormItem::text('name', 'Name')->required()->unique();
});
menu.php
Admin::menu(Games::class)->label('Games');
this error when save new record from admin
Hi.
I have a database that have a many to many relationship, and I have a multiSelect form to interact between them in every menu. The problem is that if I leave empty the multiSelect don't save it in database and leave it how it was. Sleeping-owl have that problem or is a solution for that?
Hi, I have a value in my database that can be nullable and you only can have one. How can I do a FormItem::select leaving value empty? Or I have to use a multiSelect and control that you only can have one?
Добрый день скажите почему могут не вызываться события у модели?
SiteGame::updating(function($model)
{
...
});
пробовал и через boot
public static function boot()
{
parent::boot();
static::updating(function($model)
{
...
});
}
Есть ли возможность ставить элементы формы в несколько колонок?
Каким образом можно отредактировать отображение формы?
Как вообще можно менять дизайн админки, можно ли натянуть свой шаблон, и как это сделать?
Is it possible to use it with multiple images instead of just one?
Hi!
I have a problem with wysiwyg field.
Text from ckeditor field don't passed with POST/PUT data and don't stores in database.
В модели есть поле для загрузки файла:
protected $fillable = ['presentation_file'];
Настраиваю модель для работы с файлам по документации, по при открытии формы создания в админке вылетает исключение:
Call to undefined method Illuminate\Database\Query\Builder::getPresentationFileAttribute()
(View: C:\OpenServer\domains\project.dev\vendor\sleeping-owl\admin\src\views\model\form.blade.php)
Hi SleepingOwn.
You should change the way id's are handled in the Column/Control.php ( Where the edit and destroy buttons are defined ) so that tabels/models with specific set $primaryKey attributes also are enabled.
At the moment you use :
$this->router->routeToDestroy($this->modelItem->getAlias(), $instance->id );
Which does not work if the $primaryKey is set to something else than "id".
You should use
$this->router->routeToDestroy($this->modelItem->getAlias(), $instance->getKey() ),
( $instance->getKey()
)
Which will fetch the current id of the model.
thanks in advance.
Jonas
{Название модели}/{id документа}/{название поля}/image.jpg
Спасибо Вам большое.
Is there multiple select and bulk actions?
For example. Selecting with checkboxes few rows and pushing bulk buttons. Selected row's id's are away to some action.
Модель:
<?php
use SleepingOwl\Models\SleepingOwlModel;
class SiteGame extends SleepingOwlModel {
меню:
Admin::menu('\SiteGame');;
bootstrap:
Admin::model('\SiteGame')->title('Games on site')
->columns(function ()
{
Column::string('name', 'Name');
})
->form(function ()
{
FormItem::text('name', 'Name')->required()->unique();
});
ошибка:
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Class 'SleepingOwl\WithJoin\WithJoinEloquentBuilder' not found
Open: .../vendor/sleeping-owl/admin/src/SleepingOwl/Admin/Repositories/ModelRepository.php
* @param null $params
* @return array
*/
public function tableData($params = null)
{
$baseQuery = $this->instance->newQuery()->getQuery();
/** @var WithJoinEloquentBuilder $query */
$query = new WithJoinEloquentBuilder($baseQuery);
$with = $this->modelItem->getWith();
$query->setModel($this->instance)->with($with);
Migration:
Schema::create('items', function ($table) {
// ...
$table->bigInteger('category_id')
->index()
->unsigned()
->nullable()
->default(NULL);
// ...
$table->foreign('category_id')
->references('id')
->on('categories');
});
Model configuration:
Admin::model('\Item'')->title('Items')->as('items')->with('category')->columns(function () {
Column::string('category.name', 'Category')
->append(Column::filter('category_id')->value('category.id'));
});
Generates an error if $item->category_id is null:
Trying to get property of non-object (View: /home/vagrant/Code/Laravel/vendor/sleeping-owl/admin/src/views/model/table.blade.php) in /home/vagrant/Code/Laravel/vendor/sleeping-owl/admin/src/SleepingOwl/Admin/Columns/Column/BaseColumn.php Line 216
Possible solution:
Line $result = $result->$part;
should be replaced with $result = is_null($result) ? NULL : $result->$part;
in \SleepingOwl\Admin\Columns\Column\BaseColumn::valueFromInstance()
like your demo: https://github.com/sleeping-owl/admin_demo/blob/master/app/admin/Country.php#L9
when using "->unique()", the page will always return error msg that show "module not found".
Would you please give some help?
Hello,
I created the "getTimeStamps" class in the model, but when editing from SleepingOwl the date and time are not inserted.
I used this line of code (app/admin/usuari.php).
FormItem::timestamp('fecha_inscripcion', 'Data inscripció');
And this is my code from the model (app/models/Usuari.php).
public function getTimeStamps() {
return array_merge(parent::getTimeStamps(), ['fecha_inscripcion']);
}
If I use the function getDates it only update the Time but not the Date:
public function getDates() {
return array_merge(parent::getDates(), ['data_naixement','fecha_inscripcion']);
}
What can I do to make it work?
Thank You.
First off, thank you for this amazing package!
Imagine we have a User
model and I want to add a custom method that says Export as CSV
for example.
Where can I add the method, in which controller? In a way that it'll be only accessible for authenticated admins?
Здравствуйте. Хотелось бы иметь возможность добавлять html-атрибуты к полям либо к контейнеру form-group.
Например, так:
FormItem::text('meta_title', 'Мета-тег Title')->htmlOptions(['class' => 'customclass']);
или
FormItem::text('meta_title', 'Мета-тег Title', ['class' => 'customclass']);
Hello.
I'm using your plugin and I encounter the following problem: I have a travel table that contains the source, destination, date, etc etc. Default filtering searches all the fields from the table in question and I would like to implement a filtering more specific e.g. searchable only by origin and other destination, showing me the result whose destination and origin match my search. I've been testing and looking at documents from internet but say to use a different from yours plugin.
Thank you for the attention.
I'm having a very difficult time getting your module to work; I'm sure I'm overlooking something. I really would like to get it working as it seems tremendously valuable. I've got the following in \app\admin\bootstrap.php:
Admin::model(\memehope\HealthLogTypes::class)
->as('health-log-types')
->title('Health Log Types')
->filters(function () {
ModelItem::filter('health_log_type_name')->title()->from(\memehope\HealthLogTypes::class);
}
)
->columns(function () {
Column::string('health_log_type_name', 'Type')
->append(Column::filter('health_log_type_name')->value('HealthLogTypes.health_log_type_name'));
}
)
->form(function () {
FormItem::text('health_log_type_name', 'Type');
FormItem::text('health-log_type_description', 'Description');
}
);
Note that my app namespace is memehope.
In menu.php, I've got:
Admin::menu()->url('#')->label('Health Logs')->icon('fa-medkit')->items(function() {
Admin::menu('\HealthLogTypes')->url('\health-log-types')->icon('fa-leaf')->uses('\HealthLogTypesController@index');
} );
I've tried at least a hundred variations of this, but no matter what I do, I continue to get the following error message:
ErrorException in Models.php line 48: Model with classname [\HealthLogTypes] not registered as admin module. (View: L:\xampp\htdocs\host\memehope\vendor\sleeping-owl\admin\src\views\_partials\menu.blade.php) (View: L:\xampp\htdocs\host\memehope\vendor\sleeping-owl\admin\src\views\_partials\menu.blade.php) (View: L:\xampp\htdocs\host\memehope\vendor\sleeping-owl\admin\src\views\_partials\menu.blade.php)
In my model, I've tried:
class HealthLogTypes extends \SleepingOwl\Models\SleepingOwlModel
I've also tried this:
class HealthLogTypes extends Model
(I like the idea of extending the SleepingOwlModel, but I've tried both. Neither improves the situation.
If you can give me any guidance on how I can get this to work, I'd greatly appreciate it. This model and associated views and controller was working until I tried to bring in sleeping-owl/admin. Then, the whole thing cratered.
Hi,
When I try and save using the timestamp, I get an 'The date paid is not a valid date.' Error
Eg, if I select 1st Jan 2015, I get 1/1/2015, 12:00:00 AM
but the error appears.
Funnily enough if I manually type in 2015-01-01 then this gets saved.
Regards
Nick
Hi, so thats the question. How to hide the items that are soft deleted ? Is there an option for that available with model configuration? Thx
I have a problem with saving the value of the MultiSelect. I have a multiselect declared in this way:
FormItem::multiSelect('items', 'Przedmioty')->list(\App\Models\Item::class)->value('items.order_id');
In my model I've got this mutator function:
public function items()
{
return $this->belongsToMany('App\Models\Item', 'order_items');
}
public function setItemsAttribute($items)
{
$this->items()->detach();
if ( ! $items) return;
if ( ! $this->exists) $this->save();
$this->items()->attach($items);
}
After selecting a few options and saveing I can see they are not saved and not added to the database. If I add in my mutator command die () I see that it is not even executed. I added to the database manually a few options and see that display correctly, but saveing does not work.
I am using Laravel 5. Any advices :)?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.