For some of my tables, I'd like to insert a fixed amount of rows with specific data.
This is my categories factory:
$factory->define(Category::class, function (Faker $faker) {
return [
[
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
],
[
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
],
[
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
],
[
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]
];
});
This is the seeder:
public function run() {
factory(App\Category::class, 1)->create();
}
I get this error: preg_match() expects parameter 2 to be string, array given
Is there a way to insert a fixed amount of static information into certain tables using seeding and factories?
I think you want to use Seeder with static values, if I am correct you should use
Define Category seeder
<?php
use Illuminate\Database\Seeder;
use App\Category;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$categories = [
[
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
],
[
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
],
[
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
],
[
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]
];
foreach ($categories as $category) {
Category::create($category);
}
}
}
And in DatabaseSeeder
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(CategorySeeder::class);
}
}
Now run php artisan db:seed and it will be done.
The answer of #Prafulla Kumar Sahu is by seeder, but you can override your factory values by:
$category = factory(App\Category::class)->make([
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
]);
$category = factory(App\Category::class)->make([
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
]);
$category = factory(App\Category::class)->make([
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
]);
$category = factory(App\Category::class)->make([
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]);
Related
i have data in mongodb
it is a road object that has a property and an array of points that it consists of:
my model in laravel
<?php
namespace App\Models;
use App\Traits\Uuids;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Road extends Eloquent
{
//use HasFactory;
use Uuids;
protected $connection = 'mongodb';
protected $collection = 'roads';
protected $fillable = ['id', 'roadId', 'code', 'name', 'points'];
#public $timestamps = false;
public $incrementing = false;
public function fields() : array
{
return [
'id' => [
'type' => Type::string(),
'description' => 'The identifier of the road',
],
'roadId' => [
'type' => Type::nonNull(Type::int()),
'description' => 'ID road of external database',
],
'code' => [
'type' => Type::string(),
'description' => 'code of document',
],
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => 'road name',
],
'points' => [
'name' => 'points',
'description' => 'points of road',
'type' => GraphQL::type('RoadPoints'),
'is_relation' => false
]
];
}
}
here we refer to a new type of "point on the road"
GraphQL type 'RoadPoints':
<?php
namespace App\GraphQL\Types;
use App\Models\Address;
use App\Models\RoadPoints;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Type as GraphQLType;
class RoadPointsType extends GraphQLType
{
protected $attributes = [
'name' => 'RoadPoints',
'description' => 'The points is defined by the format GeoJSON Point',
'model' => RoadPoints::class,
];
public function fields(): array
{
return [
'type' => [
'type' => Type::string(),
'description' => 'The format GeoJSON',
],
'pk' => [
'type' => Type::string(),
'description' => 'piket of point',
],
'coordinates' => [
'type' => Type::listOf(GraphQL::type('GeoJSON')),
'description' => 'The partner lat and lng',
]
];
}
}
laravel model of RoadPoints
model RoadPoints class :
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class RoadPoints extends Eloquent
{
protected $fillable = ['type', 'pk', 'coordinates'];
protected $casts = [
'coordinates' => 'array'
];
}
graphql RoadQuery :
<?php
namespace App\GraphQL\Queries;
use App\Models\Road;
use Closure;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
use App\Services\RoadService;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Facades\GraphQL;
class RoadQuery extends Query
{
private $roadService;
public function __construct(RoadService $roadService)
{
$this->roadService = $roadService;
}
protected $attributes = [
'name' => 'Road',
'description' => 'Query to Road data and points.'
];
public function type(): Type
{
return Type::listOf(GraphQL::type('Road'));
}
public function args(): array
{
return [
'id' => ['name' => 'id', 'type' => Type::string()],
'roadId' => ['name' => 'roadId', 'type' => Type::int()],
'code' => ['name' => 'code', 'type' => Type::string()],
'name' => ['name' => 'name', 'type' => Type::string()],
'lat' => ['name' => 'lat', 'type' => Type::float()],
'lng' => ['name' => 'lng', 'type' => Type::float()]
];
}
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
$fields = $resolveInfo->getFieldSelection($depth = 3);
return $this->roadService->find($args, $fields);
}
}
result:
why pk and coordinates is null ?
Please tell me how to correctly select all objects in the array (points).
error in model
change
'type' => GraphQL::type('RoadPoints'),
to
'type' => Type::listOf(GraphQL::type('RoadPoints')),
Following this documentation : https://backpackforlaravel.com/docs/4.1/crud-operation-inline-create
I try to create a link between invoices (primary) and invoices lines (secondary).
The link seems good, but I don't succeed to have the "+add" button needed to have the secondary form.
My code.
Primary class (invoiceCrudController)
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Invoice;
use Backpack\CRUD\app\Http\Controllers\CrudController;
/**
* Class InvoiceCrudController
* #package App\Http\Controllers\Admin
* #property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class InvoiceCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use SetAccesses;
protected function setupCreateOperation()
{
$this->crud->setValidation(InvoiceRequest::class);
$this->crud->addFields([
/*other cases*/
[
'name' => 'invoiceLines',
'type' => 'relationship',
'tags'=> 'invoice lines',
'ajax'=>true,
[ // specify the entity in singular
'entity' => 'invoiceLine', // the entity in singular
]
],
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
}
secondary class (invoiceLinesController)
<?php
namespace App\Http\Controllers\Admin;
use App\Models\InvoiceLine;
use Backpack\CRUD\app\Http\Controllers\CrudController;
/**
* Class InvoiceCrudController
* #package App\Http\Controllers\Admin
* #property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class InvoiceLinesCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
public function setup()
{
$this->setAccesses('invoiceLine');
$this->crud->setModel('App\Models\InvoiceLine');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/invoiceLine');
$this->crud->setEntityNameStrings('invoiceLine', 'invoiceLines');
$this->crud->addColumns([
[
'name' => 'slug',
'type' => 'text',
],
[
'name' => 'quantity',
'type' => 'number',
'default' => 1,
'wrapper' => [
'class' => 'form-group col-sm-6 col-md-6 col-lg-3 col-xl-3'
]
],
[
'name' =>'unit_vat_excluded',
'type' => 'text',
'wrapper' => [
'class' => 'form-group col-sm-6 col-md-6 col-lg-3 col-xl-3'
]
]
]);
}
protected function setupListOperation()
{
$this->crud->enableExportButtons();
CustomerCrudController::addFilterCustomer();
}
protected function setupCreateOperation()
{
$this->crud->addFields([
[
'name' => 'slug',
'type' => 'text',
'allows_null' => false,
],
[
'name' => 'quantity',
'type' => 'number',
'default' => 1,
'wrapper' => [
'class' => 'form-group col-sm-6 col-md-6 col-lg-3 col-xl-3'
]
],
[
'name' =>'unit_vat_excluded',
'type' => 'text',
'wrapper' => [
'class' => 'form-group col-sm-6 col-md-6 col-lg-3 col-xl-3'
]
]
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
protected function setupShowOperation()
{
}
public static function getColumn()
{
return [
'name' => 'invoice_line_id',
'label' => 'InvoiceLines',
'type' => 'select',
'entity' => 'invoiceLine',
'attribute' => 'pretty_print',
'model' => InvoiceLine::class,
];
}
}
I think the wrong is in your Filed definistion:
$this->crud->addFields([
/other cases/
[
'name' => 'invoiceLines',
'type' => 'relationship',
'tags'=> 'invoice lines',
'ajax'=>true,
[ // specify the entity in singular
'entity' => 'invoiceLine', // the entity in singular
]
],
since the relation is on to many (I guess) then the filed should be:
[
'type' => "relationship",
'name' => 'invoiceLines',
'ajax' => true,
'inline_create' => true,
]
I have a dataobject which I want to use on a GridField on a page but I want to limit the columns displayed. I used setQueriedColumns() to list the fields I wanted but it is still displaying the default $summary_fields from the dataobject.
MyActivity dataobject:
class MyActivity extends DataObject{
private static $db = array(
'Title' => 'Varchar(255)',
'URLSegment' => 'Varchar(512)',
'IsPublished' => 'Boolean',
'IsPublic' => 'Boolean',
'IsBooked' => 'Boolean',
'MaxDuration' => 'Int',
'PricePoint' => 'Int',
'Summary' => 'HTMLText',
'Body' => 'HTMLText',
'Sort' => 'Int'
);
private static $has_one = array(
'FileAttachment' => 'File'
);
private static $summary_fields = array(
'Title' => 'Name',
'URLSegment' => 'URLSegment',
'IsPublished' => 'Published',
'IsBooked' => 'Booked',
'Events.Count' => 'List of Events',
'Categories.Count' => ' of Categories'
);
static $has_many = array(
'Events' => 'MyEvent'
);
static $belongs_many_many = array(
'Categories' => 'MyCategory'
);
...
}
MyActivityPage:
class MyActivityPage extends Page{
public function getCMSFields(){
$fields = parent::getCMSFields();
$GridFieldConfig = GridFieldConfig_RecordEditor::create();
$fields->addFieldToTab('Root.Courses',
GridField::create(
'FileAttachment',
'Activity List',
MyActivity::get()->filter(['IsPublished' => 1])
->setQueriedColumns([
'Title',
'URLSegment',
'IsPublished'
]),
$GridFieldConfig
)
);
return $fields;
}
...
}
After thorough searching, I got what I'm looking for. Apparently, we can set the columns using GridFieldConfig then limit the fields by overriding the $summary_fields using the setDisplayFields() method in the GridFieldDataColumns object.
This could be handy to people who are looking for similar solution.
$gridField = GridField::create(
'FileAttachment',
'Activity List',
MyActivity::get()->filter(['IsPublished' => 1]),
$GridFieldConfig
)
$gridField->getConfig()
->getComponentByType('GridFieldDataColumns')
->setDisplayFields([
'Title' => 'Title',
'URLSegment' => 'URLSegment',
'IsPublished' => 'IsPublished'
]);
$fields->addFieldToTab('Root.Courses',$gridField);`
I have a plugin that generates a navbar using PHP. The folder is in project/config/menu.php
It looks like this:
<?php
return [
//HORIZONTAL MENU LAYOUT - MENU
'horizontal' => [
[
'title' => 'bar',
'link' => '/bar/all',
'active' => 'bar*',
'icon' => 'fa fa-sign-in',
],
[
'title' => 'foo',
'link' => '/foo/all',
'active' => 'foo*',
'icon' => 'fa fa-sign-out',
],
]
];
I want to add some model information.
This is my attempt:
<?php
use Auth;
$id = Auth::user()->id;
return [
//HORIZONTAL MENU LAYOUT - MENU
'horizontal' => [
[
'title' => 'bar',
'link' => '/bar/'. $id,
'active' => 'bar*',
'icon' => 'fa fa-sign-in',
],
[
'title' => 'foo',
'link' => '/foo/all',
'active' => 'foo*',
'icon' => 'fa fa-sign-out',
],
]
];
I get this error: Class 'Auth' not found. I have also tried with models:
$model = \App\Model::count();
Which gives me this error:
Call to a member function connection() on null
How do I use these models here?
laravel config loads before any other things, so instantiating model will give an error, and that error you are getting is due to no database connection information loaded during this specific config file loads. I wonder why you need to call model in config, you can simply build something like templates of menu layout like below:
<?php
return [
//HORIZONTAL MENU LAYOUT - MENU
horizontal' => [
[
'title' => 'bar',
'link' => '/bar/%d', // here %d is userId from database
'active' => 'bar*',
'icon' => 'fa fa-sign-in',
],
[
'title' => 'foo',
'link' => '/foo/all',
'active' => 'foo*',
'icon' => 'fa fa-sign-out',
],
]
];
and later replace that %d with value from model.
I would like to change the default button name on grid view On YII2
on Yii 1 we have this:
http://www.yiiframew...s-in-cgridview/
array
(
'class'=>'CButtonColumn',
'template'=>'{email}{down}{delete}',
'buttons'=>array
(
'email' => array
(
'label'=>'Send an e-mail to this user',
'imageUrl'=>Yii::app()->request->baseUrl.'/images/email.png',
'url'=>'Yii::app()->createUrl("users/email", array("id"=>$data->id))',
),
'down' => array
(
'label'=>'[-]',
'url'=>'"#"',
'visible'=>'$data->score > 0',
'click'=>'function(){alert("Going down!");}',
),
),
),
I would like something like that for Yii2
For now I would like to change only the label.
Reading the documentation for Yii2 I tried that:
[
'class' => 'yii\grid\ActionColumn',
'buttonOptions' => [
[
'name' => 'update',
'additionalOptions' => [
'label' => 'Super Update',
]
],
[
'name' => 'delete',
'additionalOptions' => [
'label' => 'Super Delete',
]
],
],
],
But it does not work.
I know I can recreate the button from scratch with :
'buttons' => [
'update' => function ($url, $model) {
$t = 'index.php?r=site/update&id='.$model->id;
return Html::button('<span class="glyphicon glyphicon-pencil"></span>', ['value'=>Url::to($t), 'class' => 'btn btn-default btn-xs']);
},
],
But I do not want to do that.
thanks
buttonOptions will be applied to all default buttons, you can't separate them, but it's possible to apply general options (to all buttons):
'class' => 'yii\grid\ActionColumn',
'buttonOptions' => [
'title' => 'This is custom title for default 3 buttons',
],
If you want to use custom HTML options, you'll have to create new class, extend ActionColumn and overwrite (2) protected methods, for example:
<?php
namespace app\models;
use yii\grid\ActionColumn;
use yii\helpers\Html;
use Yii;
class customActionColumn extends ActionColumn
{
/**
* Initializes the default button rendering callbacks.
*/
protected function initDefaultButtons()
{
$this->initDefaultButton('view', 'eye-open', [
'title' => 'Super View',
]);
$this->initDefaultButton('update', 'pencil', [
'title' => 'Super Update',
]);
$this->initDefaultButton('delete', 'trash', [
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
'title' => 'Super Delete'
]);
}
/**
* Initializes the default button rendering callback for single button
* #param string $name Button name as it's written in template
* #param string $iconName The part of Bootstrap glyphicon class that makes it unique
* #param array $additionalOptions Array of additional options
* #since 2.0.11
*/
protected function initDefaultButton($name, $iconName, $additionalOptions = [])
{
if (!isset($this->buttons[$name]) && strpos($this->template, '{' . $name . '}') !== false) {
$this->buttons[$name] = function ($url, $model, $key) use ($name, $iconName, $additionalOptions) {
$title = Yii::t('yii', ucfirst($name));
$options = array_merge([
'title' => $title,
'aria-label' => $title,
'data-pjax' => '0',
'title' => 'atata'
], $additionalOptions, $this->buttonOptions);
$icon = Html::tag('span', '', ['class' => "glyphicon glyphicon-$iconName"]);
return Html::a($icon, $url, $options);
};
}
}
}
Now in GridView you just need to specify custom class and that's all.
[
'class' => app\models\customActionColumn::className(),
],