I have created a migration, whichi should create tables for my database, and insert default admin user.
<?php
//use Yii;
use yii\db\Migration;
use yii\db\Schema;
/**
* Class m180616_200856_create_tables
*/
require_once( __DIR__.'/../config.php');
class m180616_200856_create_tables extends Migration
{
public function up()
{
if (Yii::$app->db->schema->getTable("users",true)===null) {
$this->createTable('users', [
'id' => $this->primaryKey(),
'username' => $this->string(),
'password' => $this->string(),
'authKey' => $this->string(),
'accessToken' => $this->string()
]);
$this->insert('users',array(
'username'=> SUPERUSER_LOGIN,
'password' => md5(SUPERUSER_PASS ),
'authKey' => 'key',
'accessToken' => ''
));
}
}
public function down()
{
echo "m180616_200856_create_tables cannot be reverted.\n";
return false;
}
}
When i run this migration, i get the error:
*** applying m180616_200856_create_tables
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\db\mysql\Schema::getTable()'
If i include use Yii i get the error:
*** applying m180616_200856_create_tables
PHP Warning 'yii\base\ErrorException' with message 'The use statement with non-compound name 'Yii' has no effect'
So it seems i cannot use Yii namespace inside migration, how can i check if table exists?
In migration you can check if table does not exist in this way:
$tableName = $this->db->tablePrefix . 'users';
if ($this->db->getTableSchema($tableName, true) === null) {
It will usually work the same as:
$tableName = Yii::$app->db->tablePrefix . 'users';
if (Yii::$app->db->getTableSchema($tableName, true) === null) {
And yes, you can use Yii in migrations, it just does not make any sense to import class from global namespace if you're already in global namespace.
Related
So I have the following code:
class PageSection extends Model {
protected $table = "PageSection";
const TYPE_CURATED = 0;
const TYPE_AUTOMATED = 1;
public function list() {
return $this->morphTo('list', 'entity_type', 'id_Entity');
}
}
then in AppServiceProvider.php I have the following:
use App\PageSection;
use App\PageSectionGroup;
use App\PageListEntry;
use App\RSSFeed;
use App\Shortcut;
use App\RSSEpisode;
use App\PageList;
use App\AutomatedList;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
Relation::morphMap([
'Section' => PageSection::class,
'SectionGroup' => PageSectionGroup::class,
PageSection::TYPE_CURATED => PageList::class,
PageSection::TYPE_AUTOMATED => AutomatedList::class,
PageListEntry::TYPE_FEED => RSSFeed::class,
PageListEntry::TYPE_SHORTCUT => Shortcut::class,
PageListEntry::TYPE_EPISODE => RSSEpisode::class
]);
}
Then I have a test route in my api routes that checks to see if the list is being loaded, and it returns null: (Yes, I've verified that the section itself exists)
Route::get('/test', function() {
$section = PageSection::with(['list', 'type'])->find(1);
// this returns null
return $section->list;
});
My database schema for PageSection is such that entity_type tells what the model is, and id_Entity is the foreign key for that model, which is named 'id' on the referenced table.
The other relations defined in morphMap are working properly, yet for some reason the list() relationship in PageSection is not. I'm not sure what I'm doing wrong here.. any help would be appreciated.
Ok, so I figured out what was going on. It's probably a bug with Laravel's morphMap. I was using 0 for the PageSection::TYPE_CURATED constant, which is a falsey value. When I switched to:
Relation::morphMap([
'PageList' => PageList::class,
'AutomatedList' => AutomatedList::class,
'Section' => PageSection::class,
'SectionGroup' => PageSectionGroup::class,
PageListEntry::TYPE_FEED => RSSFeed::class,
PageListEntry::TYPE_SHORTCUT => Shortcut::class,
PageListEntry::TYPE_EPISODE => RSSEpisode::class
]);
it all worked fine. Seems like Laravel doesn't like the value 0.
I'm staring with Laravel and I'm having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value
(SQL: insert into `addresses` (`updated_at`, `created_at`)
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))
As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model
{
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
}
And the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Addresses;
use App\Customers;
class AddressesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request){
$create = Addresses::create([
'name' => request('name'),
'city' => request('city'),
'suburb' => request('suburb'),
'street' => request('street'),
'o_number' => request('o_number'),
'i_number' => request('i_number'),
'postal_code' => request('postal_code'),
'phone_s' => request('phone_s'),
'email_s' => request('email_s'),
'google_map' => request('google_map'),
'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
]);
$success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
}
}
Echo the request() values works! So I'm missing right now, I have some other Models and Controller working good in the same way. Please Help!
This error show because you the NAME field is required on your database. Try to edit your migration script and put default value on this field or make it nullable.
eg.
$table->string('name')->nullable();
OR
$table->string('name')->default('');
Then run a migration refresh.
Goto "phpmyadmin" >> "Variables" then find "sql_mode" edit and remove "STRICT_ALL_TABLES or STRICT_TRANS_TABLES"
It is working for me.
Hope it will help for All.
This is late answer for this question, but it might help for others.
This error can be occurred due to error in $fillable data in modal.
You can try using
protected $guarded = []
instead of
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
But You have to validate the data that you passed within the controller.
The error occurs due to the strict mode of MYSQL5.7. Please change your config/database.php in the connections.mysql section by putting 'strict' => false.
I solved it using save()
$addresses = new Addresses;
$customer_id = Customers::where('code',$request->session()->get('customer_code'))->first()->id;
$addresses->name = $request->name;
$addresses->city = $request->city;
$addresses->suburb = $request->suburb;
$addresses->street = $request->street;
$addresses->o_number = $request->onumber;
$addresses->i_number = $request->inumber;
$addresses->postal_code = $request->postal_code;
$addresses->phone_s = $request->phone_s;
$addresses->email_s = $request->email_s;
$addresses->google_map = $request->map;
$addresses->customer_id = $customer_id;
$success = $addresses->save() ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
It's working properly
When you use the nullable() method on a field, that field will default to NULL.
For example, add this to your migration file:
$table->string('name')->nullable();
Update:
You can add:
$table->string('name')->nullable()->default(null);
You can check Null option in table structure, like this -
Make sure request() has key 'name'.Replace request('name') to random string and try again.
In my case I forgot to change - this is my code on my Controller
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->name = $request->input('message');
$message->save();
}
I made a duplication of the 'name' that's why it happened and made this
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->message = $request->input('message');
$message->save();
}
This way the solution to the problem.
I was having this problem because I didn't add a correct column under $fillable list.
class Chirp extends Model
{
use HasFactory;
protected $fillable = [
'message', // This line should be added.
];
}
I have a Post Model with these fields :
post_id
post_title
post_content
post_content_full
author
Now I want to use laravel sedders and model factories to create fake fa_IR localized data and insert to posts table.
For that I wrote this in database/factories/ModelFactory.php:
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'post_title' => $faker->sentence,
'post_content' => $faker->paragraph,
'post_content_full' => $faker->paragraph(3),
'author' => $faker->name
];
});
Then I created a PostsTableSeeder class like this :
use Illuminate\Database\Seeder;
class PostsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run ()
{
factory(App\Post::class, 5)->create();
}
}
And in AppServiceProvider.php added below codes to register function :
$this->app->singleton(FakerGenerator::class, function () {
return FakerFactory::create('fa_IR');
});
But After running the seed , laravel uses default locale (en_US) and ignores fa_IR.
I do not know what else to do.
Update:
Even I changed in DEFAULT_LOCALE const vendor/fzaninotto/faker/src/Faker/Factory.php to fa_IR Nothing changed.
Not all faker methods are supported in every language, from what a quick lookup of the documentation says, the Company and Address provider are supported in the fa_IR localization
Try this way
$factory->define(App\Post::class, function () {
$faker = Faker\Factory::create('fa_IR');
return [
'post_title' => $faker->sentence,
'post_content' => $faker->paragraph,
'post_content_full' => $faker->paragraph(3),
'author' => $faker->name
];
});
You need to change the faker locale in your app config file.
First run this
php artisan make:factory PostFactory
Do like this
$faker = \Faker\Factory::create();
Then use like this
$sub_g->name = $faker->name();
$sub_g->country = $faker->country();
$sub_g->state = $faker->state;
Thank me later.
I'm using Laratrust and try implements:
I created these files
App\MyMenuFilter.php
<?php
namespace App;
use JeroenNoten\LaravelAdminLte\Menu\Builder;
use JeroenNoten\LaravelAdminLte\Menu\Filters\FilterInterface;
class MyMenuFilter implements FilterInterface
{
public function transform($item, Builder $builder)
{
if (isset($item['permission']) && Laratrust::can($item['permission'])) {
return false;
}
return $item;
}
}
I changed this
config\adminlte.php
'menu' => [
'MAIN NAVIGATION',
[
'text' => 'Blog',
'url' => 'admin/blog',
'permission' => 'create-post', // Here
],
#code
]
'filters' => [
#code
//JeroenNoten\LaravelAdminLte\Menu\Filters\GateFilter::class,
App\MyMenuFilter::class,
],
But show this error:
Class 'App\Laratrust' not found (View: /var/www/html/multi-auth/vendor/jeroennoten/laravel-adminlte/resources/views/page.blade.php)
Simplest way
if (isset($item['permission']) && \Laratrust::can($item['permission'])) {
return false;
}
or you can
use Laratrust;
if (isset($item['permission']) && Laratrust::can($item['permission'])) {
return false;
}
the use statement should be right at the top before class definition and the condition will obviously be in your method
It appears that Laratrust is a package residing in vendor directory thats why trying to get it under the \App location will throw an error.
You dont import the App\Laratrust in your namespace. Add use App\Laratrust; to the top of your class and it should work.
This is a wierd situation because magento is loading my backend model, its just not calling it when I load and save it. I know this because 1. I see it in my database, 2. when I rename my backend model, my test case fails. Here is my code
It saves my values just fine and completely ignores my afterload and beforesave methods.
TEST CASE
<?php
class Super_Base_Test_Controller_Test extends EcomDev_PHPUnit_Test_Case_Controller {
const DEFAULTSTORE = 1;
public function setUpMocks() {
$this->setCurrentStore(1);
$customer = Mage::getSingleton('customer/customer')
->load(1);
$customer->setCoinBalance(20)
->save();
}
public function setUp() {
$this->setUpMocks();
$data = array(
'customer_id'=>1,
'message'=>'this is a test message',
'income'=>20,
'created_at'=>'9/11/84',
'updated_at'=>'9/11/84',
'current'=>1
);
$this->getRequest()->setParams($data);
}
protected function getTearDownOperation() {
return PHPUnit_Extensions_Database_Operation_Factory::TRUNCATE();
}
}
backend model
<?php
/**
* Created by PhpStorm.
* User: numerical25
* Date: 3/8/14
* Time: 6:22 PM
*/
class Super_Coin_Model_Customer_Attribute_Coinbalance extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract {
protected function _afterLoad()
{
if (!is_array($this->getValue())) {
$value = $this->getValue();
$this->setValue(empty($value) ? false : unserialize($value));
}
}
protected function _beforeSave() {
if (is_array($this->getValue())) {
$this->setValue(serialize($this->getValue()));
}
}
public function setCoinAmount($amount) {
$this->setValue($amount);
}
}
installation file
$eavsetup->addAttribute('customer', 'coin_balance', array(
'input' => 'text',
'type' => 'decimal',
'label' => 'Customer Coin Balance',
'backend' => 'coin/customer_attribute_coinbalance',
'global' => 1,
'visible' => 1,
'required' => 0,
'user_defined' => 1, ));
When I set break points, the system completly ignores my methods.
Look at abstract class Mage_Eav_Model_Entity_Attribute_Backend_Abstract. It contains the following public methods: beforeSave() and afterLoad().
There are no _afterLoad() and _beforeSave() methods in that class