I am using laravel 9. I am trying to generate some fake users to boost my db using factoreis and seeders.
When i try to seed my db i get this error
Object of class Faker\UniqueGenerator could not be converted to string
at D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
661▕ $value,
662▕ match (true) {
663▕ is_int($value) => PDO::PARAM_INT,
664▕ is_resource($value) => PDO::PARAM_LOB,
➜ 665▕ default => PDO::PARAM_STR
666▕ },
667▕ );
668▕ }
669▕ }
1 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
PDOStatement::bindValue(Object(Faker\UniqueGenerator))
2 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:540
Illuminate\Database\Connection::bindValues(Object(PDOStatement))
this my UserFactory
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'username' => fake()->unique(),
'company' => fake()->sentence(),
'position' => fake()->sentence(),
'bio' => fake()->realText($maxNbChars = 100),
'picture' => fake()->imageUrl(90, 90),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => Hash::make('password'), // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
After looking arround for a while I found that fake()->unique() does not return a string. So I tried to convert it to string but It also gives me a error saying Unknown format "toString" in Faker\Generator.php:731
[Problem solved]
I just had to edit my UserFactory username to this
'username' => fake()->unique()->text(16),
I would like in My ContactController.php (which manages my US contact) replace the recipient's email address with a value get from the database in a table called Student ..
'''
<?php
namespace App\Http\Controllers;
use Mail;
use App\Models\Student;
use App\Models\ContactUs;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function showForm(Request $request)
{
return view('welcome');
}
public function Infos(Request $request)
{
$info = Student::find(1)->value('monemail');
//// do something
}
public function storeForm(Request $request)
{
///get value of $info
$this->validate($request, [
'name' => 'required|max:100',
'email' => 'required|email',
'phone' => 'required|numeric',
'subject' => 'required|max:100',
'message' => 'required|max:400'
]);
ContactUs::create($request->all());
\Mail::send('email', array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'phone' => $request->get('phone'),
'subject' => $request->get('subject'),
'form_message' => $request->get('message'),
), function ($message) use ($request) {
$message->from($request->email);
//change test#test.fr by value of $info in Infos method
$message->to('test#test.fr', 'Message de Transport Parisien')->subject($request->get('subject'));
});
return back()->with('success', 'Thank.');
}
}
'''
I do not remember how to pass the value of a result to another method in the same controller
Thank for any help or suggestion.
I found that as a solution. It's working. If someone has another solution can be more elegant.
'''
function ($message) use ($request) {
$info = Student::find(1)->value('monemail');
$message->from($request->email);
$message->to($info, 'Message from me')->subject($request->get('subject'));
'''
Have a good day.
I am new to yii2 and I don't exactly know how to apply same rules of insert into update. Here is my rules for insert and I want all rules to effect on update too.
public $tag;
public function rules()
{
return [
[['user_id', 'name', 'address', 'state'], 'required'],
[['user_id'], 'integer'],
[['tag'], 'safe'],
[['name'], 'string', 'max' => 30],
[['address'], 'string', 'max' => 250],
[['state'], 'string', 'max' => 255],
];
}
Adding 'on' => 'update' doesn't effect in my code. Sorry for my english. Thanks.
The default rules are applied in the creation and update, you only have to create new rules if you want different behaviors between update and create.
To apply the rules just make a $model->validate() to check the rules, see this example of the documentation of yii2
$model->load(\Yii::$app->request->post());
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
You can add validation rules to yii model like this
public function rules(){
return [
[['boolean_var'],'boolean'],
[[ 'range_in_string'],'required'],
[['default_value'],'default','value'=>'DEFAULT VALUE'],
[['integer_var'],'integer'],
[['double_var'],'double'],
[['number_min'],'number','min'=>10],
[['number_max'],'number','max'=>100],
[['number_min_max'],'number','min'=>10,'max'=>100],
[['file_image'],'image'],
[['file_var'],'file','types'=>['gif','jpg']],
[['date_var'],'date', 'format'=>'d-m-yy'],
[['min_string'],'string','min'=>10],
[['max_string'],'string','max'=>10],
[['min_max_string'],'string','min'=>5,'max'=>10],
['min_max_string2', 'string', 'length' => [4, 10]],
['email_var','email'],
['url_var','url'],
[['unique_var'],'unique'],
[['filter_trim'],'filter','filter'=>'trim'],
[['filter_trim'],'filter','filter'=>'strtolower'],
['filter_custom_function', 'filter', 'filter' => function ($value) {
// your concept
if($value=='')
return '';
return 'Value Changed';}],
['range_in_min_max', 'in','range'=>range(5,20)],
['range_in','in','range'=>['en','fr','zn'],'strict'=>false], //strict false
['range_in_string','in','range'=>['EN','FR','ZN'],'strict'=>true],
['custom_validation','custom_function_validation'],
[['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],
[['password','date_var'],'safe'],
];
}
if you need to trigger only when updating but not creating, you can add a scenario like this
public function rules()
{
return [
// username, email and password are all required in "update" scenario
[['username', 'email', 'password'], 'required', 'on' => 'update'],
// username and password are required in "login" scenario
[['username', 'password'], 'required', 'on' => 'login'],
];
}
and in your action before calling validate add the scenario
// scenario is set as a property
$model = new User;
$model->scenario = 'update';
my first question to this site is a little difficult to describe.
I am quite new to Symfony, startet with 3.2 and updated recently to 3.3.5 (not sure if relevant for the problem).
I tried to use CraueFormFlowBundle (multistep form bundle) but cannot get it to work.
The problem is that trying to access the flow results in an exception:
Error: Call to a member function getCurrentRequest() on null
Symfony\Component\Debug\Exception\ FatalErrorException
in vendor/craue/formflow-bundle/Form/FormFlow.php (line 191)
Line 191 shows: $currentRequest = $this->requestStack->getCurrentRequest();
Modifying the FormFlow.php with dump line shows that $this->requestStack is null.
I have not enough knowledge about this bundle to know where to start looking for the problem.
The flow definition is based on the location example:
namespace EngineeringBundle\Form;
use Craue\FormFlowBundle\Form\FormFlow;
use Craue\FormFlowBundle\Form\FormFlowInterface;
class SelectExaminationFlow extends FormFlow
{
/**
* {#inheritDoc}
*/
protected function loadStepsConfig()
{
dump("loadStepsConfig");
return array(
array(
'label' => 'engineering.discipline',
'form_type' => new SelectExaminationStep1Form(),
),
array(
'label' => 'engineering.date',
'form_type' => new SelectExaminationStep2Form(),
'skip' => function($estimatedCurrentStepNumber, FormFlowInterface $flow) {
return $estimatedCurrentStepNumber > 1 && !$flow->getFormData()->canHaveRegion();
},
),
array(
'label' => 'confirmation',
),
);
}
The form definition is also quite simple and works without problems:
class SelectExaminationStep1Form extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
dump("buildForm");
$builder
->add('id', HiddenType::class)
->add('discipline', EntityType::class, array(
'class' => 'EngineeringBundle:Discipline',
'choice_label' => 'disciplineName',
'label' => 'engineering.discipline.label'
)
);
}
public function getName() {
return $this->getBlockPrefix();
}
public function getBlockPrefix() {
return 'createEngineeringStep1';
}
}
services.yml:
EngineeringBundle\Form\SelectExaminationFlow:
parent: craue.form.flow
autowire: false
autoconfigure: false
public: true
engineering.form_flow:
alias: EngineeringBundle\Form\SelectExaminationFlow
public: true
Controller:
/**
* #Route("create", name="engineering_create")
*/
public function createAction()
{
return $this->processFlow(new ExaminationDate(), $this->get('engineering.form_flow'));
}
Thanks in advance
Sebastian
I was having the same problem, resolved it by adding a constructor to vendor/craue/formflow-bundle/Form/FormFlow.php with the following content:
public function __construct(RequestStack $requestStack, FormFactoryInterface $formFactory, DataManagerInterface $dataManager, EventDispatcherInterface $eventDispatcher) {
$this->formFactory = $formFactory;
$this->requestStack = $requestStack;
$this->dataManager = $dataManager;
$this->eventDispatcher = $eventDispatcher;
}
Make sure to place it after all setter-methods. Problem seems to be related to a symfony update.
I looked at the documentation for rbac in Yii and thought I understood how it worked until I actually tried it.
This is the rule for checking whether the author of the post is trying to get the authorization for an action:
class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
* #param string|integer $user the user ID.
* #param Item $item the role or permission that this rule is associated with
* #param array $params parameters passed to ManagerInterface::checkAccess().
* #return boolean a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
return isset($params['model']) ? $params['model']->createdBy == $user : false;
}
}
This is how I am trying to use the rule and Yii's rbac:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (\Yii::$app->user->can('update', ['model' => $model])) {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
}
However, I get this when I try to edit a Post:
Getting unknown property: app\models\Post::createdBy
So I thought I had to replace createdBy with userId which is a column in the table Post and I am getting a blank page meaning it doesn't work. So I am trying to guess what $user is.
I also tried:
return isset($params['model']) ? $params['model']->userId == $user->id : false;
and I am getting: Trying to get property of non-object.
What should I do to make it work? The doc seemed to suggest you just had to plug the conditional inside the controller action to make it work, but it doesn't seem to be the case at all.
var dump:
object(app\models\Post)[75]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'userId' => int 1
'title' => string 'test' (length=4)
'content' => string 'lol' (length=3)
'dateCreated' => null
'dateUpdated' => null
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'userId' => int 1
'title' => string 'test' (length=4)
'content' => string 'lol' (length=3)
'dateCreated' => null
'dateUpdated' => null
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) => null
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
null
The first error says, that you don't have a createdBy property in your Post model. Do you?
The second error is about trying to get a property of non-object variable. Could you show var_dump($params['model']); var_dump($user); before the return?