getting following error " 150 "Foreign key constraint is incorrectly formed"" on the console - sql

I've checked several times against other projects and I just cannot see what's wrong.
I attach my code:
Schema::table('datos', function (Blueprint $table) {
$table->bigInteger('sensor_id')->change();
$table->foreign('sensor_id')->references('id')->on('sensores')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('datos', function (Blueprint $table) {
$table->dropForeign(['sensor_id']);
});
}

Your function will be look like :
public function up()
{
Schema::create('datos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('sensor_id')->unsigned();
$table->foreign('sensor_id')->references('id')->on('sensores')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('datos');
}

make sure the sensor_id is unsignedBigInteger and move nullable method before change

Related

Laravel Many To Many Relationships update

I am trying to make Many To Many Relationships with Laravel. but where I'm stuck is, when post is updated, how do I update the pivot table?
posts migration
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('body');
$table->timestamps();
});
languages migration
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
language_post migration
Schema::create('language_post', function (Blueprint $table) {
$table->id();
$table->foreignId('language_id')->constrained();
$table->foreignId('post_id')->constrained();
$table->timestamps();
$table->boolean('active')->default(false);
});
Language Model
public function posts()
{
return $this->belongsToMany(Post::class)
->withTimestamps();
}
Post Model
public function languages()
{
return $this->belongsToMany(Language::class)
->withTimestamps()
->withPivot('active');
}
PostController
class PostController extends Controller
{
public function index()
{
return Post::with('languages')->get();
}
public function store(Request $request)
{
$post = new Post();
$post->title = $request->title;
$post->body = $request->body;
$post->save();
$post->languages()->attach(explode(',', $request->language));
}
public function show($id)
{
$post = Post::find($id);
$post->languages;
return $post;
}
public function update(Request $request, $id)
{
}
public function destroy($id)
{
$postDelete = Post::find($id);
$postDelete->languages()->detach();
return Post::destroy($id);
}
}

Encode password easyadmin v3

I have my user that I can manage from my administration panel, I can change the password, but the problem is that in the database it is not encrypted. It is in clear in the database, Save you how I could do it so that it is not anymore? I give you my user entity as well as the crud user And I use the easyadmin v3 and symfony 5 bundle.
My entity User
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
*/
private $prenom;
/**
* #ORM\Column(type="string", length=255)
*/
private $nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $telephone;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $aPropos;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $facebook;
/**
* #ORM\OneToMany(targetEntity=Realisation::class, mappedBy="user", orphanRemoval=true)
*/
private $realisations;
public function __construct()
{
$this->realisations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* #see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getTelephone(): ?string
{
return $this->telephone;
}
public function setTelephone(string $telephone): self
{
$this->telephone = $telephone;
return $this;
}
public function getAPropos(): ?string
{
return $this->aPropos;
}
public function setAPropos(?string $aPropos): self
{
$this->aPropos = $aPropos;
return $this;
}
public function getFacebook(): ?string
{
return $this->facebook;
}
public function setFacebook(?string $facebook): self
{
$this->facebook = $facebook;
return $this;
}
/**
* #return Collection|Realisation[]
*/
public function getRealisations(): Collection
{
return $this->realisations;
}
public function addRealisation(Realisation $realisation): self
{
if (!$this->realisations->contains($realisation)) {
$this->realisations[] = $realisation;
$realisation->setUser($this);
}
return $this;
}
public function removeRealisation(Realisation $realisation): self
{
if ($this->realisations->removeElement($realisation)) {
// set the owning side to null (unless already changed)
if ($realisation->getUser() === $this) {
$realisation->setUser(null);
}
}
return $this;
}
public function __toString()
{
return $this->nom;
}
/* public function __toString(){
return $this->nom;
}*/
}
<?php
namespace App\Controller\Admin;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
class UserCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return User::class;
}
public function configureFields(string $pageName): iterable
{
return [
IntegerField::new('id','ID')->onlyOnIndex(),
TextField::new('email'),
TextField::new('password'),
TextField::new('nom'),
TextField::new('telephone'),
TextField::new('aPropos'),
TextField::new('facebook'),
];
}
}
This could be helpful ...
<?php
namespace App\Event\Subscriber;
use App\Entity\BackendUser;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
class EasyAdminHooksSubscriber implements EventSubscriberInterface {
/**
* #var UserPasswordEncoderInterface
*/
private $passwordEncoder;
/**
* #var ContainerInterface
*/
private $container;
/**
* EasyAdminSubscriber constructor.
*
* #param UserPasswordEncoderInterface $passwordEncoder
* #param ContainerInterface $container
*/
public function __construct(UserPasswordEncoderInterface $passwordEncoder, ContainerInterface $container) {
$this->passwordEncoder = $passwordEncoder;
$this->container = $container;
}
public static function getSubscribedEvents(): array {
return array(
BeforeEntityUpdatedEvent::class => array('preUpdateEntity')
);
}
/**
* #param BeforeEntityUpdatedEvent $event
*
* #noinspection PhpUnused
*/
public function preUpdateEntity(BeforeEntityUpdatedEvent $event) {
$entity = $event->getEntityInstance();
if($entity instanceof BackendUser) {
$this->preUpdateBackendUser($entity);
}
}
/**
* #param BackendUser $be_user
*/
private function preUpdateBackendUser(BackendUser &$be_user) {
$plain_password = $be_user->getPlainPassword();
if(!empty($plain_password)) {
$new_password = $this->passwordEncoder->encodePassword($be_user, $plain_password);
$be_user->setPassword($new_password);
$be_user->setPlainPassword();
}
}
}
Here's a solution I found while trying to create/edit users from my web app's admin dashboard (Symfony 5.3 and EasyAdmin v3). I found it in the EasyAdmin issue tracker over on Github.
You will need to add a plain password field to you User class and set the appropriate getter & setter methods.
/**
* #var string
*/
private $plainPassword;
/**
* #return string
*/
public function getPlainPassword(): string
{
return $this->plainPassword;
}
Add event listeners to listen to create/edit form submission events, extract the plain password from the submitted form data and then hash it.
/** #var UserPasswordHasherInterface */
private $hasher;
public function createEditFormBuilder(EntityDto $entityDto, KeyValueStore $keyValueStore, AdminContext $context): FormBuilderInterface
{
$formBuilder = parent::createEditFormBuilder($entityDto, $keyValueStore, $context);
$this->addEncodePasswordEventListener($formBuilder);
return $formBuilder;
}
public function createNewFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
{
$formBuilder = parent::createNewFormBuilder($entityDto, $formOptions, $context);
$this->addEncodePasswordEventListener($formBuilder);
return $formBuilder;
}
/**
* #param FormBuilderInterface $formBuilder
*/
public function addEncodePasswordEventListener(FormBuilderInterface $formBuilder)
{
$formBuilder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event){
/** #var User $user */
$user = $event->getData();
if ($user->getPlainPassword()) {
$user->setPassword($this->hasher->hashPassword($user, $user->getPlainPassword()));
}
});
}
Then finally you need to render the appropriate form fields.
public function configureFields(string $pageName): iterable
{
return [
# other fields
Field::new('plainPassword', 'New Password')->onlyOnForms()
->setFormType(RepeatedType::class)
->setFormTypeOptions([
'type' => PasswordType::class,
'first_options' => ['label' => 'New password'],
'second_options' => ['label' => 'Repeat Password']
])->setRequired(true)
];
}
Hope someone finds this useful.
You can add plain password field in User entity:
private ?string $plainPassword= '';
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(?string $plainPassword): void
{
$this->plainPassword = $plainPassword;
}
Add password updater in User repo:
public function setNewPassword(PasswordAuthenticatedUserInterface $user, string $plainPassword): void
{
$hashedPassword = $this->hasher->hashPassword($user, $plainPassword);
$user->setPassword($hashedPassword);
$this->_em->persist($user);
$this->_em->flush();
}
And override update/persist methods In UserCrudController:
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updatePassword($entityInstance);
parent::updateEntity($entityManager, $entityInstance);
}
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updatePassword($entityInstance);
parent::persistEntity($entityManager, $entityInstance);
}
private function updatePassword(User $user): void
{
if ($user->getPlainPassword() == '') return;
$this->userRepository->setNewPassword($user, $user->getPlainPassword());
}
It's work in Symfony 5.4.2 / EasyAdmin 3.5.19

PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

I am using laravel 6.2, connection is SQL. I am creating two tables, with 'one to many relationship.' Table 'users', and 'managers', where each user will have one manager, and each manager will have more than one user.
Below is the user table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->integer('totalBalance')->default(21);
$table->integer('annualBalance')->default(15);
$table->integer('casualBalance')->default(6);
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('manager_id')->unsigned()->index();
$table->foreign('manager_id')->references('id')->on('managers')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
below is the managers migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManagersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('managers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('managers');
}
}
below is user model:
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
public function manager()
{
return $this->belongsTo('App\Manager');
}
}
below is the manager model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Manager extends Model
{
protected $primaryKey = 'id';
public function users()
{
return $this->hasMany('App\User');
}
}
I am getting the below error:
I have tried a lot of things, I saw from other questions online, including changing the type of id (from BigInteger, and integer, and changing engine in database.php to ''InnoDB', and splitting the user model to two parts (2nd part for adding the foreign key).
One thing I saw online (but didn't figure out how to implement), is to change the order of timestamp, as some other suggested that this error might be related to this.
Any suggestion?
This is happening because the user migration is run before creating the manager's table. so Change the migration with the following content will help you to create the foreign key under the manager table.
// user migration file
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->integer('totalBalance')->default(21);
$table->integer('annualBalance')->default(15);
$table->integer('casualBalance')->default(6);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
// managers migration file
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManagersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('managers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('manager_id')->unsigned()->index();
$table->foreign('manager_id')->references('id')->on('managers')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('managers');
}
}

Laravel - SQLSTATE[42S22] - Foreign key

I'm trying to implements a 'has one' relation but this error prevent me to save the token.
Migrations :
class CreatePasswordTokensTable extends Migration
{
public function up()
{
Schema::create('password_tokens', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('token');
});
}
...
}
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password')->default('');
$table->string('remember_token', 100)->default('');
$table->boolean('active')->default(false);
$table->timestamps();
});
}
...
}
Models :
class User extends Model
{
public function passwordToken()
{
return $this->hasOne('App\Models\PasswordToken');
}
}
class PasswordToken extends Model
{
public function user() {
return $this->belongsTo('App\Models\User');
}
}
Commands -
Strange user_id appear after the save call -
Error :
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL:
insert into users (email, id, user_id, updated_at,
created_at) values (email, 1, 1, 2017-04-18 10:05:47, 2017-04-18
10:05:47))'
If you are using Laravel 5.3 Try this :
Schema::create('password_tokens', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInt('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('token');
});
I think you can update your model like this:
class User extends Model
{
public function passwordToken(){
return $this->hasOne('App\Models\PasswordToken','user_id', 'id');
}
}
class PasswordToken extends Model
{
public function user()
{
return $this->belongsTO('App\Models\User', 'user_id', 'id');
}
}
Hope this work for you!
Did you fill $table and $fillable attributes at your models?
Did you try the following?
$user->save();
$token->user_id = $user->id;
$token->save();

Query Exception in Connection.php

this is my migration code..... or schema you can say
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
// $table->string('name');
$table->string('to');
$table->string('from');
// $table->string('email')->unique();
$table->string('mobile')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
the Error is shown up when i run this on laravel :
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('to');
$table->string('from');
$table->string('mobile')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
try to use this code,
Also check setting of database related in env file and database.php