Laravel - SQLSTATE[42S22] - Foreign key - sql

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();

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);
}
}

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

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

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');
}
}

how to get all data from 4 relation table in laravel 5.5

I am new on laravel and I was stuck at this problem, where I can't get all data from relation table,
This my ERD :
This my Krs.php model :
protected $fillable = ['nim','nip','kode_mk','absen','uts','uas'];
protected $table = 'krs';
public function mahasiswa(){
return $this->hasMany('App\Mahasiswa');
}
public function dosen(){
return $this->hasMany('App\Dosen');
}
public function makul(){
return $this->hasMany('App\Matakuliah');
}
This my Matakuliah.php model :
protected $fillable = ['kode_mk','makul','sks'];
protected $table = 'mata_kuliah';
public function krs(){
return $this->belongsTo('\App\Krs');
}
This my Dosen.php model :
protected $fillable =['nip','nama','jeniskelamin','alamat','notlp'];
protected $table='dosen';
public function krs(){
return $this->belongsTo('App\Krs');
}
This my Mahasiswa.php model :
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','email','tempat','tanggal','link','id_jurusan'];
protected $table = 'mahasiswa';
public function jurusan(){
return $this->hasOne('App\Jurusan');
}
public function krs(){
return $this->belongsTo('App\Krs');
}
and here is my KrsController.php :
public function index()
{
$data = Krs::with(['mahasiswa','dosen','makul'])->first()->toArray();
return view('Krs.krsIndex',compact('data'));
}
how to get all data from all table? for example I want get nama from mahasiswa ? I don't know how to do it...I was try and searching from last night but still not change anything.. sorry for my bad grammar.thanks before
Edit 1
cannot get data from mata_kuliah table
this my blade syntax for print the data
{{ $data['makul'] }}
Using with() function :
$client_profile = Client::where([['cid', '=', $cid], ['is_delete', '=', 0]])->with(['status', 'group_no', 'caseworker', 'clerk', 'active_attendants'])->first()->toArray();
below is my model :
class Client extends Model {
public function status() {
return $this->hasOne('App\Models\Status', 'sid', 'status');
}
public function group_no() {
return $this->hasOne('App\Models\ClientGroups', 'cgid', 'group_no');
}
public function caseworker() {
return $this->hasOne('App\Models\Caseworker', 'cwid', 'caseworker_name');
}
public function clerk() {
return $this->hasOne('App\Models\Supervisorsnurses', 'snid', 'clerk');
}
public function active_attendants() {
return $this->hasMany('App\Models\AssociatedTask', 'cid');
}
public function location() {
return $this->hasOne('App\Models\Locations', 'lid', 'location');
}
}

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