Creating a joined table with laravel - sql

I am using Laravel 6. I want to create a joined table named meeting_user that should connect the tables meetings and users. That's considering that a user could participate to many meetings and a meeting could have many users.
users:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('username')->unique();
$table->string('password');
$table->enum('permission', array(0, 1, 2));
$table->enum('is_active', array(0, 1))->default(1);
$table->rememberToken();
$table->timestamps();
});
meetings:
Schema::create('meetings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('description');
$table->string('id_room');
$table->date('date');
$table->time('start_hour');
$table->time('end_hour');
$table->enum('is_active', array(0, 1))->default(1);;
$table->timestamps();
$table->foreign('id_room')->references('id')->on('rooms');
});
I would like to create this table with a migration and furthermore I would like that when a user creates a meeting with many users and so inserts a new row to the "meetings" table, even the new "meeting_user" table be dynamically filled in adding new rows. Is there a way to do that with Laravel?

you have to create a third table
called for example "user_meetings"
and it's migration will be
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('meeting_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')-
>onDelete('cascade');
$table->foreign('meeting_id')->references('id')->on('meetings')-
>onDelete('cascade');
and then put the relation in "user" model
public function meetings()
{
return $this->belongsToMany(Meeting::class, 'user_meetings', 'user_id', 'meeting_id');
}
and the relation in "meeting" model
public function users()
{
return $this->belongsToMany(User::class, 'user_meetings', 'meeting_id', 'user_id');
}
and the code of "adding" meetings in the controller will be
$user->meetings()->attach($request->meetings);
return redirect()->back()->with('success', 'successfull');
and "edit"
$checker->meetings()->sync($request->meetings);
return redirect()->back()->with('success', 'successfull');
and "delete"
$checker->meetings()->detach();
i hope these steps will help you

Related

Return result from pivot table

I have multiple campaigns, that can be assigned to multiple users. Basically, they have belongsToMany relation both ways.
I would like to print out the results on the page, that only belongs to that specific user, based on the pivot table.
Models:
User model:
public function campaign()
{
return $this->belongsToMany(Campaign::class, 'campaign_user');
}
Campaign model:
public function users()
{
return $this->belongsToMany(Gift::class, 'campaign_user');
}
Migration of pivot table:
public function up()
{
Schema::create('campaign_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');;
$table->foreignId('campaign_id')->constrained()->onDelete('cascade');
});
}
Incorrect Controller:
public function index(Request $request)
{
$data = Campaign::withCount('gifts');
$data->where('user_id', $request->user()->id)->get();
return view('subscribes.index', ['data' => $data]);
}
Basically, all I need, is to return specific campaigns, that the client has subscribed only, based on the pivot table/user id. Thus, editing this Controller.
I still face lots of issues with Eloquent models and pivot tables, and I would be very thankful, for any assistance in regards to it.
This will make more sense if you rename the relationship campaign() to it's plural campaigns() on your User model.
Once you have the relationships set up, you can access campaigns for the user straight from the user object.
$user = $request->user();
$data = $user->campaigns;
Note also, if your user is authenticated, you can access them easily like:
$user = auth()->user();
So your index method in your controller would be
public function index(Request $request)
{
$user = $request->user();
$data = $user->campaigns;
return view('subscribes.index', ['data' => $data]);
}

Error SQLSTATE[HY000]: General error: 1005 Can't create table in ACL Permission and Role Laravel 8

do not be tired. My program has a problem, please check the following code. thank you
The codes give this error:
SQLSTATE[HY000]: General error: 1005 Can't create table term_laravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)
Uploaded photo error link: enter image description here
Important Note: migration failed to create the table. So with the command migrate: reset, migrate: fresh does not delete. The table must be manually referenced by phpmyadmin and the table
I remove role_user, permisstions, roles.
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('title')->nullable();
$table->timestamps();
});
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('title')->nullable();
$table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('user_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
$table->primary(['role_id','user_id']);
});
Schema::create('permission_role', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('permission_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('permission_id')
->references('id')
->on('permissions')
->onDelete('cascade')
->onUpdate('cascade');
$table->primary(['permission_id','role_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('permission_and_roles');
}
}

Change date format in Laravel migration

I want to change the date format from 1990-01-30 to 30/01/1990 straight from my migration. I get the following error when I try to migrate with seeding from factory.
Invalid datetime format: 1292 Incorrect date value: '30/01/1990' for
column 'dob' at row 1
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('fname');
$table->string('lname');
$table->string('phone')->unique();
$table->date('dob')->format('d/m/Y');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Declare in model:
class ModelName extends Model
{
protected $casts = [
'created_at' => 'datetime:d/m/Y', // Change your format
'updated_at' => 'datetime:d/m/Y',
];
}
You can't do that within a migration. You will need to use Carbon and format the date in your Model instead.

SQLSTATE[HY000]: General error: 1 unknown column "user_id" in foreign key definition

I have this error when i run :
php artisan migrate:fresh
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1 unknown column "user_id" in foreign key definition (SQL:
create table "users" ("id" integer not null primary key autoincrement,
"name" varchar not null, "email" varchar not null, "username" varchar
not null, "email_verified_at" datetime null, "password" varchar not
null, "remember_token" varchar null, "created_at" datetime null,
"updated_at" datetime null, foreign key("user_id") references
"users"("id") on delete cascade))
I'm following a video tutorial on youtube, and the code of the tutorial is this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
If I copy and paste this code I have the error. So i searched on stackoverflow and I've found this solution:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
Schema::table('profiles', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('profiles');
}
This is my users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('users');
}
But today, when i run php artisan migrate:fresh I had this error again.
How can I solve?
Thanks
As others have mentioned, user_id isn't a column in your users table, but you are trying to create an index on it. This line:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
belongs in the profiles table creation schema and not in the users table creation schema.
The full code:
// create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
// create_profiles_table.php <-- migrate AFTER users table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
The error is clearly mention here:
foreign key("user_id") references "users"("id") on delete cascade)
and you don't have a column with name user_id
The syntax is:
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns) <-- this must be a column in the table
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
but in your case user_id column is not available in the query. So either add the that column or remove this constraint code and try again.
The reason for this problem is that the profile table was created before the user table.
I have a trick for problem solve.
You should rename migration files in the migration directory.
for example let my file names be like this
2019_06_10_000001_create_users_table.php
2019_06_10_000002_create_profiles_table.php
first user table is created when you run "artisan migrate or migrate:fresh"
why? because first created migration file is user file.You should look carefully
2019_06_10_000001 -> users table name
2019_06_10_000002 -> profiles table name
Solution:
So u just need to do this: rename "user" table and name it numerically smaller than the "profiles" table.So problem will solve.
Other solution:
delete all migration files after run them respectively this commands.
php artisan make:migration create_users_table
php artisan make:migration create_profiles_table
Try this;
public function up()
{
Schema::dropIfExists('profiles');
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
That is the migration. Before you are able to run it; delete the row for 'CreateProfilesTable' in the migrations table.

Search by Max of Value in Eloquent Database Laravel

How convert this Raw SQL to Eloquent Database in my API Controller?
What i'm tried is i wanna get data from Two Tables from My API Controller.
First: Formc_image Table which is general information about data
Second: Formc_image_detail which is detail and path of data
They are related by ID.
This is my API Controller FormCController.php
SELECT *
FROM formc_image_detail
WHERE id_tps=$id_tps AND jenis_pemilihan=$election_id
AND versi = (SELECT MAX(versi) FROM formc_image WHERE id_tps=id_tps AND jenis_pemilihan=$election_id)
ORDER BY no_lembar ASC
This is my Model FormCImageDetail
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImageDetail extends Model
{
protected $table = 'formc_image_detail';
public function formc_image(){
return $this->belongsTo('App\Models\FormCImage');
}
}
This is my FormCImage Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImage extends Model
{
protected $table = 'formc_image';
}
I was make this code in My API Controller:
return response(FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->orderBy('no_lembar', 'ASC')->paginate(100)->jsonSerialize(), Response::HTTP_OK);
But it still error.
This is my Migration:
Schema::create('formc_image', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->string('jenis_pemilihan');
$table->timestamps();
}
Schema::create('formc_image_detail', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->integer('no_lembar');
$table->string('jenis_pemilihan');
$table->char('url_image', 100);
$table->timestamps();
}
Use this:
return FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->where('versi', function($query) use($election_id) {
$query->select(DB::raw('max(versi)'))
->from('formc_image')
->whereColumn('id_tps', 'formc_image_detail.id_tps')
->where('jenis_pemilihan', $election_id);
})
->orderBy('no_lembar')
->paginate(100);