one to many relationship laravel - php

I am making a one to many relationship, when I try to save it, it asks me to enter the FK should not I do it automatically?
class AlternativesCompetitorsImage extends Model
{
public function alternativecompetitors()
{
return $this->belongsTo(AlternativesCompetitor::class,'id');
}
}
class AlternativesCompetitor extends Model
{
public function alternativescompetitorsimages(){
return $this->hasMany(AlternativesCompetitorsImage::class,'alter_comp_id');
}
}
Controller
$ci = isset($id_image) ? $step->alternativescompetitorsimages : new AlternativesCompetitorsImage();
if( $request->hasFile('fileImg')){
$fileRequests = request()->file('fileImg');
$count = 0;
foreach ($fileRequests as $fileRequest) {
$keyCanvas = $c->key;
$stepKey = $stepType->key;
$public= public_path();
$directory =DIRECTORY_SEPARATOR."canvas".DIRECTORY_SEPARATOR.$keyCanvas.DIRECTORY_SEPARATOR.$stepKey;
$newName = "image".$count.".png";
Storage::deleteDirectory($directory);
$path = $fileRequest->storeAs("public".$directory,$newName);
$str = str_replace("\\", '/', $path);
$ci->url_img = $str;
!isset($id_image) ? $step->alternativescompetitorsimages()->save($ci) : $step->alternativescompetitorsimages()->update($ci->toArray());
DB::commit();
$count++;
}
Migrations
class CreateAlternativesCompetitorsImages extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('alternatives_competitors_images',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('url_img',100);
$table->integer('alter_comp_id')->unsigned();
$table->timestamps();
$table->foreign('alter_comp_id')->references('id')->on('alternatives_competitors');
});
}
class CreateAlternativesCompetitors extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('alternatives_competitors',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('step_id')->unsigned();
$table->string('valueA',10);
$table->string('valueB',10);
$table->timestamps();
$table->foreign('step_id')->references('id')->on('steps');
});
}
Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity
constraint violation: 1048 Column 'alter_comp_id' cannot be null (SQL:
insert into alternatives_competitors_images (url_img,
alter_comp_id, updated_at, created_at) values
(public/canvas/de939a01-1438-4aff-bb23-eb4f68653f5f/TEAM/image0.png, ,
2018-03-27 23:31:12, 2018-03-27 23:31:12)) in
C:\xampp\htdocs\canvas\vendor\laravel\framework\src\Illuminate\Database\Connection.php:647

You didn't stablish alter_comp_idto be nullable, and later you try to create a row with that column null. So... Either specify that value
$ci->alternativecompetitors()->associate($keyCanvas);
, or re-migrate the table to allow that field to be null, like this:
$table->integer('alter_comp_id')->unsigned()->nullable();

Related

Spatie / Permissions throwing constraint failure when assigning Roles using UUID

I have a Laravel 9 project where I am using UUID's. I have just installed the Spatie Permissions package and followed the instructions to use it with UUID's ... But when I try to assignRole I am getting the following error;
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`project`.`model_has_roles`, CONSTRAINT `model_has_roles_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE) (SQL: insert into `model_has_roles` (`model_id`, `model_type`, `role_id`) values (1d6535d1-01f0-43b4-8701-4e3c76ad1587, App\Models\User, 0))
I think it might be something to do with the Spatie migration which comes with the package. I have updated it as per https://spatie.be/docs/laravel-permission/v5/advanced-usage/uuid#content-migrations .. as below;
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\PermissionRegistrar;
class CreatePermissionTables extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$teams = config('permission.teams');
if (empty($tableNames)) {
throw new \Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
}
if ($teams && empty($columnNames['team_foreign_key'] ?? null)) {
throw new \Exception('Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
}
Schema::create($tableNames['permissions'], function (Blueprint $table) {
$table->uuid('id'); // permission id
$table->string('name'); // For MySQL 8.0 use string('name', 125);
$table->string('guard_name'); // For MySQL 8.0 use string('guard_name', 125);
$table->timestamps();
$table->primary('id');
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], function (Blueprint $table) use ($teams, $columnNames) {
$table->uuid('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MySQL 8.0 use string('name', 125);
$table->string('guard_name'); // For MySQL 8.0 use string('guard_name', 125);
$table->timestamps();
$table->primary('id');
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $teams) {
$table->uuid(PermissionRegistrar::$pivotPermission);
$table->string('model_type');
$table->uuid($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign(PermissionRegistrar::$pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], PermissionRegistrar::$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([PermissionRegistrar::$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $teams) {
$table->uuid(PermissionRegistrar::$pivotRole);
$table->string('model_type');
$table->uuid($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign(PermissionRegistrar::$pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], PermissionRegistrar::$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([PermissionRegistrar::$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) {
$table->uuid(PermissionRegistrar::$pivotPermission);
$table->uuid(PermissionRegistrar::$pivotRole);
$table->foreign(PermissionRegistrar::$pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign(PermissionRegistrar::$pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([PermissionRegistrar::$pivotPermission, PermissionRegistrar::$pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
$tableNames = config('permission.table_names');
if (empty($tableNames)) {
throw new \Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
}
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
}
I have a trait for UUID which is as follows;
<?php
declare(strict_types=1);
namespace App\Concerns;
use Illuminate\Support\Str;
trait HasUuid
{
protected static function boot(): void
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
public function getIncrementing(): bool
{
return false;
}
public function getKeyType(): string
{
return 'string';
}
}
I have this on my User model, and also I have extended the Role and Permission model which now looks like this;
<?php
declare(strict_types=1);
namespace App\Models;
use App\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\Permission\Models\Role as SpatieRole;
class Role extends SpatieRole
{
use HasFactory;
use HasUuid;
}
The code that it is failing on is the following which is a standard user create, but the assignRole is where it seems to be failing;
User::create([
'name' => 'Super Admin',
'email' => 'super-admin#example.com',
'password' => Hash::make('password'),
])->assignRole('super-admin');
Any help would be greatly appreciated.
I managed to figure this out if anyone has the same issue.
As I am extending the Role and Permission model, this needs to be reflected in the config/permission.php file
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => \App\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => \App\Models\Role::class,
],

Laravel/MariaDB: errno 150 "Foreign key constraint is incorrectly formed"

I'm on Laravel 5.4, PHP 5.6, Ubuntu 18.04, MariaDB 10.4.8. When I run php artisan migrate, I get:
In Connection.php line 647:
SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke
y constraint is incorrectly formed") (SQL: alter table `comments` add constraint `comments_post_id_foreign` forei
gn key (`post_id`) references `posts` (`id`))
In Connection.php line 449:
SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke
y constraint is incorrectly formed")
I'm trying to use https://github.com/klisl/laravel-comments. Before trying to perform a migration with this package I had created DB at phpMyAdmin, had configured .env by adding DB name and stuff, had successfully run php artisan migrate, php artisan make:auth and php artisan make:controller AuthController. Then, after running php artisan vendor:publish --provider="Klisl\Comments\CommentsServiceProvider" I get 2 new files in migrations folder: date_number_CreateCommentsTable.php and date_number_ChangeCommentsTable.php
Here's source from these 2 files:
CreateCommentsTable.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class CreateCommentsTable
*/
class CreateCommentsTable extends Migration
{
/** #return void */
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->text('text');
$table->integer('parent_id')->nullable(); //разрешаем null;
$table->boolean('status')->default(config('comments.show_immediately'));
$table->timestamps();
});
}
/** #return void */
public function down()
{
Schema::dropIfExists('comments');
}
}
ChangeCommentsTable.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class ChangeCommentsTable
*/
class ChangeCommentsTable extends Migration
{
/** #return void */
public function up()
{
Schema::table('comments', function (Blueprint $table) {
$table->integer(config('comments.key_field'))->unsigned();
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
if(config('comments.user')){
$table->integer('user_id')->unsigned()->nullable(); //разрешаем null
$table->foreign('user_id')->references('id')->on('users');
}
});
}
/** #return void */
public function down()
{
Schema::table('comments', function (Blueprint $table) {
//
});
}
}
So then I run php artisan migrate and get the error I've written about above.
I've already tried adding ->unsigned() at CreateCommentsTable. Also I've tried to put the foreign keys out of the function at ChangeCommentsTable like this:
/** #return void */
public function up()
{
Schema::table('comments', function (Blueprint $table) {
$table->integer(config('comments.key_field'))->unsigned();
if(config('comments.user')){
$table->integer('user_id')->unsigned()->nullable(); //разрешаем null
}
});
Schema::table('comments', function ($table){
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
});
Schema::table('comments', function ($table){
if(config('comments.user')){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
}
});
}
/** #return void */
public function down()
{
Schema::dropForeign([config('comments.key_field')]);
Schema::dropForeign(['user_id']);
Schema::table('comments', function (Blueprint $table) {
//
});
}
and this:
Schema::table('comments', function ($table){
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
if(config('comments.user')){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
}
});
As any of didn't work out, I decided to post the default version of source above. If you help me with this, you really save my day c:
UPD: Here's source from CommentController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use App\Comment;
use App\Post;
class CommentController extends Controller
{
/**
* Processing form - AJAX
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
$data = $request->except('_token', 'comment_post_ID', 'comment_parent');
//adding fields with same names like in table (models)
$data['post_id'] = $request->input('comment_post_ID');
$data['parent_id'] = $request->input('comment_parent');
$data['status'] = config('comments.show_immediately');
$user = Auth::user();
if($user) {
$data['user_id'] = $user->id;
$data['name'] = (!empty($data['name'])) ? $data['name'] : $user->name;
$data['email'] = (!empty($data['email'])) ? $data['email'] : $user->email;
}
$validator = Validator::make($data,[
'post_id' => 'integer|required',
'text' => 'required',
'name' => 'required',
'email' => 'required|email',
]);
$comment = new Comment($data);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
$post = Post::find($data['post_id']);
$post->comments()->save($comment);
$data['id'] = $comment->id;
$data['hash'] = md5($data['email']);
$data['status'] = config('comments.show_immediately');
$view_comment = view(env('THEME').'.comments.new_comment')->with('data', $data)->render();
return response()->json(['success'=>true, 'comment'=>$view_comment, 'data'=>$data]);
}
}
There is a foreign key missing in the comments table, give this a try:
Schema::create('comments', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')
I am not sure how to add a foreign key in laravel 5.4 let me know if this works.
I haven't had posts table so the problem was solved by adding it. I'll mark this answer as a correct when it's possible.

How to fix the error occurs on adding a table referring a foreign key in laravel?

(2/2) QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'productdesc_id' in 'field list' (SQL: insert into subSalesPackage (salesPackage, productdesc_id, updated_at, created_at) values (, 0, 2017-08-22 04:45:24, 2017-08-22 04:45:24))
This is the error occurs, on adding the table.
I have two table ProductDescription(table1) and subSalesPackage(table2). And here table1 has a primary key field as descid and also foreign key field as product_id referred from another table.
table2 has a primary key field as id and foreign key field as product_descid referred from the table1(ie.,descid).
But, when I am trying to add the table2 values, it shows error(mentioned #top)
Model for ProductDescription:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class productDescription extends Model
{
//
protected $table="ProductDescription";
protected $connection="mysql";
public function productPricing()
{
return $this->belongsTo(priceInfo::class);
}
**public function salesPackage()
{
return $this->hasMany(packageModel::class);
}**
}
Model2->for subSalesPackage
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class packageModel extends Model
{
//
protected $table="subSalesPackage";
protected $connection="mysql";
public function productdesc(){
return $this->belongsTo('App\productDescription');
}
}
Controller:
public function addProductDetails(Request $formdescription,$dataId)
{
$description=new productDescription;
$description->deviceCategoryId=$dataId;
$description->descid=$this->getproductDescriptionId();
$description->skillSet =$formdescription->input('skillSet');
$description->rechargable=$formdescription->input('rechargable');
//$product->productPricing()-save($priceInfo);
//$product->productDetails()->save($description);
$description->save();
$salesPackage=new packageModel;
$salesPackage->salesPackage=$formdescription->input('package');
$salesPackage->productdesc()->associate($description);
//$salesPackage->product_description()->associate($description);
$salesPackage->save();
return response()->json([
'modelName' => $formdescription->mname,
'colour' => $formdescription->colour,
'rechargable' => $formdescription->rechargable,
'batteryType' => $formdescription->batteryType
]);
}
This is the controller code I have tried for adding both the tables.
Schema-table1:
public function up()
{
//
Schema::create('ProductDescription', function (Blueprint $table) {
$table->engine='InnoDB';
$table->string('descid')->primary();
$table->string('product_id');
$table->string('deviceCategoryId');
$table->string('modelName');
$table->string('Height');
$table->string('rechargable');
$table->foreign('product_id')->references('id')-
>on('productPriceDetails')->onUpdate('cascade')-
>onDelete('cascade');
$table->timestamps();
$table->index(['descid']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('ProductDescription');
}
Schema-table2:
public function up()
{
//
Schema::create('subSalesPackage', function (Blueprint $table) {
$table->increments('id');
$table->string('product_descid');
$table->string('salesPackage');
$table->foreign('product_descid')->references('descid')-
>on('ProductDescription')->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
$table->index(['id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('subSalesPackage');
}
You should specify foreign key, since you are not following naming convention of Eloquent. please follow the code.
public function productdesc(){
return $this->belongsTo('App\productDescription','product_descid');
}
You need to rename product_descid to productdesc_id in subSalesPackage table and check.

Laravel eloquent unconventional column not working

Hi laravel is not inserting correct value in pivot table for many to many case.
Here my first model is
class ShippingAddress extends Eloquent {
protected $guarded = array('id');
protected $table = 'shippingAddress';
public function mwsOrder()
{
return $this->belongsToMany('MwsOrder',
'mwsOrders_shippingAddress',
'Address_id',
'AmazonOrderId'
);
}
}
Second Model is
class MwsOrder extends Eloquent {
protected $table = 'mwsOrders';
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
}
EER Diagram
Now when i run this
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress;
$address->name = 'Naruto Uzumaki';
$address->save();
$address->mwsOrder()->attach($mwsOrder);
//$mwsOrder->shippAddress()->save($address);
laravel throws error and this is what laravel trying to run the query
(SQL: insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 3))
What i need is to generate this query
insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 'Eve 6')
Update:
Schema are:
Schema::create("shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("Name");
$table->timestamps();
});
Schema::create("mwsOrders", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId")->unique();
$table->timestamps();
});
Schema::create("mwsOrders_shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId");
$table->foreign("AmazonOrderId")->references("AmazonOrderId")->on('mwsOrders');
$table->integer("shipping_address_id")->unsigned();
$table->foreign("shipping_address_id")->references('id')->on('shippingAddress');
$table->timestamps();
});
At first change the shippAddress to this:
// Specify the primary key because it's not conventional id
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
Then you may try this:
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress(['name' => 'Naruto Uzumaki']);
$mwsOrder->shippAddress()->save($address); // Save and Attach

Laravel Eloquent after save id becomes 0

It's a table migrated from https://github.com/lucadegasperi/oauth2-server-laravel
In the table oauth_clients, the field data type of id is varchar(40), not int.
$name = Input::get('name');
$id = str_random(40);
$secret = str_random(40);
$client = new oauthClient;
$client->name = $name;
$client->id = $id;
$client->secret = $secret;
$client->save();
After save(); the $client->id become '0', not the string I assigned.
That makes the following relation table save fail.
$endpoint = new OauthClientEndpoint(array('redirect_uri' => Input::get('redirect_uri));
$client->OauthClientEndpoint()->save($endpoint);
I checked the $client->id: after save, it becomes 0 and I get an error including this one:
(SQL: insert into `oauth_client_endpoints` (`redirect_uri`, `client_id`, `updated_at`, `created_at`) values (http://www.xxxxx.com, 0, 2014-09-01 11:10:16, 2014-09-01 11:10:16))
I manually saved an endpoint to prevent this error for now. But how do I resolve this issue?
Here's my model:
class OauthClient extends Eloquent {
protected $table = 'oauth_clients';
public function OauthClientEndpoint(){
return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
}
}
class OauthClientEndpoint extends Eloquent {
protected $table = 'oauth_client_endpoints';
protected $fillable = array('redirect_uri');
public function OauthClient(){
return $this->belongsTo('OauthClient', 'client_id', 'id');
}
}
class CreateOauthClientsTable extends Migration {
public function up() {
Schema::create('oauth_clients', function (Blueprint $table) {
$table->string('id', 40);
$table->string('secret', 40);
$table->string('name');
$table->timestamps();
$table->unique('id');
$table->unique(array('id', 'secret'));
});
}
public function down() {
Schema::drop('oauth_clients');
}
}
class CreateOauthClientEndpointsTable extends Migration {
public function up() {
Schema::create('oauth_client_endpoints', function (Blueprint $table) {
$table->increments('id');
$table->string('client_id', 40);
$table->string('redirect_uri');
$table->timestamps();
$table->foreign('client_id')
->references('id')->on('oauth_clients')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down() {
Schema::table('oauth_client_endpoints', function ($table) {
$table->dropForeign('oauth_client_endpoints_client_id_foreign');
});
Schema::drop('oauth_client_endpoints');
}
}
When you are setting your own ID and not using auto_increment be sure to add public $incrementing = false; to that model. In your case you want:
class OauthClient extends Eloquent {
public $incrementing = false;
protected $table = 'oauth_clients';
public function OauthClientEndpoint(){
return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
}
}
This is a tiny red block in the huge Laravel documentation:
Note: Typically, your Eloquent models will have auto-incrementing keys. However, if you wish to specify your own keys, set the incrementing property on your model to false.

Categories