Is there a way to set auto increment back to 1 before seeding a table?
I empty the table before seeding it and if I didn't do migrate:refresh before seeding it then it continues the auto increment of the ID from the last position, e.g., 4.
Table seed:
public function run()
{
DB::table('products')->delete();
// Product table seeder
$product = new \App\Product([
'category_id' => 1,
'image_path' => '/images/products/1/000001.jpg',
'title' => 'test',
]);
$product->save();
}
Creating the table:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('image_path');
$table->string('title');
$table->timestamps();
});
Try this:
DB::statement('SET FOREIGN_KEY_CHECKS=0');
DB::table('products')->truncate();
Instead of
DB::table('products')->delete();
If you're using make:migration or make:model -m commands to create a migration, Laravel is creating down() method with dropIfExists() clause:
public function down()
{
Schema::dropIfExists('products');
}
So when you run migrate:refresh command, Laravel will drop the table and will recraete it for you.
Also, you have foreign keys in the table, so you need to use dropForeign() first:
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropForeign('products_category_id_foreign');
});
Schema::dropIfExists('products');
}
Related
I have this migration:
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
}
And now I want to add a new column, and looks like this:
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->string('pathlogo')->default('/');
$table->timestamps();
});
}
How can I make just an 'add column' on Laravel? I don't want to do php artisan migrate:refresh, or restart and then make again seed.
Now I have some data in DB which not exist on seed I just want to make a new column.
You need to change Schema::create to Schema::table (because you are not creating a table, just selecting it), and then your only line in that function should be:
$table->string('pathlogo')->default('/')->after('slug');
after will ensure the column is positioned how you want.
If you are still in development, ie. you don't have data in the table, you should just rollback all your migrations and edit the original.
Create a new migration and Use that as your up function:
public function up()
{
Schema::table('clients', function (Blueprint $table) {
$table->string('pathlogo')->default('/');
});
}
them migrate as normal.
I have the following migration:
public function up()
{
Schema::create('topics_to_subscriptions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('topic_id')->unsigned();
$table->integer('subscription_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
$table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
});
}
My undersatnding is that when using onDelete('cascade'), if I delete a subscription, then all associated TopicsToSubscriptions will be delete.
When I run App\Subscription::truncate(); all the subscriptions are deleted correctly from subscriptions table but no data is deleted from topics_to_subscriptions. what am I doing wrong?
You shouldn't be able to truncate a table referenced by foreign keys. I suspect your foreign keys never got applied correctly.
https://laravel.com/docs/5.4/migrations#foreign-key-constraints
public function up()
{
Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('topic_id')->unsigned();
$table->integer('youtube_subscription_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('youtube_topics')->onDelete('cascade');
$table->foreign('youtube_subscription_id')->references('id')->on('youtube_subscriptions')->onDelete('cascade');
});
}
My migration is like this :
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id_test');
$table->string('name', 50);
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::drop('tests');
}
I want to change data type and add column in table test. Then update table in database. I edit like this :
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->string('id_test', 18);
$table->string('name', 50);
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::drop('tests');
}
Then I run : php artisan migrate:refresh
I lost my data in database
Is there any people who can help me?
Create a new migration file using below command :
php artisan make:migration name_of_your_file
And its function should be like this
public function up()
{
Schema::table('tests', function($table) {
$table->renameColumn('id_test', 'id');
$table->string('id_test', 18);
});
}
public function down()
{
Schema::table('tests', function($table) {
$table->dropColumn('id_test');
});
}
Now just run below command
php artisan migrate
Note : Dont use refresh it deletes the data
To know more about Laravel Migration refer : https://laravel.com/docs/5.3/migrations#modifying-columns
I'm still thinking is there a ways how can I create a custom pivot table name? Because I created a documents and users table has a many to many relationship with document_user which is my pivot table and this table was created for received document that user created. And I'm planning to create a another pivot table for document and user this table was for sent documents so I can have history. See my code below.
create_document_user_table
public function up()
{
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('dateModified')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
}
documents_table
public function up()
{
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('middle_name');
$table->string('email');
$table->string('username');
$table->string('address');
$table->string('password');
$table->string('remember_token');
$table->integer('role_permission_id')->unsigned();
$table->foreign('role_permission_id')->references('id')->on('roles_permissions_dt')->onDelete('cascade');
$table->timestamps();
});
}
This works well inserting records to my pivot table. What I'm planning to achieve is every-time I inserted a records for documents this will inserted too in my custom pivot table not only in my document_user pivot table. Any help would appreciated! Thanks for your info or tips.
UPDATE
#Mina thanks for the tips that you given but actually this is my insert or save for my pivot table. How can I inserted this in my revisions table?
DocumentController
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$user = Auth::user();
foreach($request->recipient_id as $recipientId)
{
$document->recipients()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
return redirect()->back();
}
You can call your pivot tables as you like.
As mentioned previously, to determine the table name of the
relationship's joining table, Eloquent will join the two related model
names in alphabetical order. However, you are free to override this
convention. You may do so by passing a second argument to the
belongsToMany method:
return $this->belongsToMany('App\Role', 'user_roles');
(Eloquent: Relationships #Many To Many)
In your case you would need to define the relations like this:
class User extends Model
{
// other stuff
createdDocuments()
{
return $this->belongsToMany('App\Document', 'document_user_created');
}
sentDocuments() // or receivedDocuments()
{
return $this->belongsToMany('App\Document', 'document_user_sent');
}
// other stuff
}
class Document extends Model
{
// other stuff
createdByUsers()
{
return $this->belongsToMany('App\User', 'document_user_created');
}
sentToUsers() // or sentFromUsers() or whatever it does mean
{
return $this->belongsToMany('App\User', 'document_user_sent');
}
// other stuff
}
You do not need another pivot table. You need a table like that:
public function up()
{
Schema::create('revisions', function (Blueprint $table) {
$table->increments('id');
$table->integer('document_id')->unsigned();
//Rest of table structure
$table->foreign('document_id')->references('id')->on('document_user')->onDelete('cascade');
$table->timestamps();
});
}
When you need to create a new Revision:
$document = new Document;
//add $document attributes
$user->documents()->save($document);
$document->recipients->each(function($recipient){
$id = $recipient->pivot->id;
Revision::create(['document_id'=>$id]);
})
I'm trying to implement where I need to insert or save the current user that logged in. Inserting the recipient into user_id column works well but I need to manipulate who send the data I need to get the user id. I have two tables users and documents with a pivot table document_user.
users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('username');
$table->string('password');
$table->string('remember_token');
});
documents table
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
document_user - pivot table
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
DB Design:
Note! I only insert few column in my users table migration just to save a line of text.
Model
User
public function documents()
{
return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');
}
Document
public function recipients()
{
return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');
}
Inserting records based on the user's choice to pivot table works well. But when I try to rollback my migration and alter my pivot table to this.
$table->integer('sender_id')->unsigned();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
I get a error it says:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`webdev`.`document_user`, CONSTRAINT `document_user_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `document_user` (`document_id`, `user_id`) values (34, 10))
How can I achieve inserting the current user in my pivot table? So I can track who sends and receive the data. Any help would appreciated! Cheers!
UPDATE 1:
Thanks to #Dastur for solving my issue.
document_user table
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
I'm just having a hard time getting the id of the current user and insert this into sender_id column. Still don't have any idea to do this because I need to tracked the created documents of the users.
DocumentController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Document;
use App\Models\User;
use DB;
use Auth;
class DocumentController extends Controller
{
public function getDocuments()
{
//GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
$resultRecipient = DB::table('users')->where('id', '!=', Auth::id())->get();
//GETTING ALL THE CATEGORIES.
$resultCategory = DB::table('categories')->get();
//VIEW
return view ('document.create')->with('resultRecipient', $resultRecipient)->with('resultCategory', $resultCategory);
}
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync($request->recipient_id, false);
return redirect()->back();
}
}
UPDATE 2: According to #Dastur I need to create a another Model for my pivot table which is document_user.
UserDocument (Model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserDocument extends Model
{
protected $table = 'document_user';
}
I looked around a bit online, and found this post on laracasts: http://laravel.io/forum/09-18-2014-foreign-key-not-saving-in-migration. Also, this error is normally thrown when your trying to get a null value from another table and put it into a row that isn't nullable.
Edit:
What your doing here is very strange, I still think the pivot table isn't a smart option. Here's exactly what I would do:
Migrations:
First, I would create my users migration, simple enough:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('username');
$table->string('password');
$table->rememberToken();
});
Next I would create my documents table:
Schema::create('documents', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id');
$table->integer('user_id');
$table->integer('sender_id');
$table->dateTime('dateRecieved')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamps();
});
Models:
In your user and category model you need the following method:
public function documents() {
$this->hasMany(/* Path to your document model */);
}
Finally, in your document model you need the following methods:
public function category() {
$this->belongsTo(/* Path to your category model */);
}
public function user() {
$this->belongsTo(/* Path to your user model */);
}
Document Controller
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
/*
* This part not exactly sure what to do, because of I don't know what
* know what the difference is between the sender and the user, please
* elaborate.
*/
}