Retrieve data by foreign key - mysql

I have two tables in my database Users and Complains.
Users table :
id | name | password
Complains table
id | user_id | title | body
The user_id is a foreign key. How do I retrieve title and body from the complains table based on the user_id?
This is what I have so far but I cannot retrieve data specific to the user_id
My User Model :
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'surname', 'regnumber', 'course', 'department', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My Profile Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Complain;
use App\Feedback;
use App\Item;
use Illuminate\Support\Facades\Redirect;
use Session;
use Auth;
class ProfileController extends Controller
{
public function profile($user_id){
$user = User::whereId($user_id)->first();
$complains = Complain::paginate(2);
return view('user.profile', compact('user', 'complains'));
}
}
My view:
#foreach($complains as $complain)
<div>
<h3 class="operator-complain-title">Title: </h3>
<p>{{ $complain->title }}</p>
<h3 class="operator-complain-title">Complain:</h3>
<p>{{ $complain->body }}</p>
</div>
<hr>
#endforeach
Anyone with any ideas please share.

You'll want to setup a one-to-many relationship as outlined here: https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
Once you have the correct methods in place, Eloquent will find relations when you do something like $user->complains.
class User extends Model
{
/**
* Get the complains for the User.
*/
public function complains()
{
return $this->hasMany('App\Complain');
}
}
class Complain extends Model
{
/**
* Get the User for the Complain.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}

This is my users table migration :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
This is my complains table migration :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateComplainsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('complains', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('complains');
}
}
This is the migration I used to add foreign key to complains table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddForeignKeyToComplains extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('complains', function (Blueprint $table) {
$table->integer('user_id')->after('id')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('complains', function (Blueprint $table) {
$table->dropColumn('user_id');
});
}
}

Related

Can't change data type in database using Laravel migration

I'm trying to change the data type (from string to boolean) of 5 columns in my database, but it's showing an error that i have no idea what is the meaning.
My migration is this:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeFieldDataType extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('categoria_pneu')->change();
$table->boolean('categoria_dicas')->change();
$table->boolean('categoria_servicos')->change();
$table->boolean('categoria_dicas_gerais')->change();
$table->boolean('categoria_variados')->change();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('categoria_pneu');
$table->dropColumn('categoria_dicas');
$table->dropColumn('categoria_servicos');
$table->dropColumn('categoria_dicas_gerais');
$table->dropColumn('categoria_variados');
});
}
}
The erros that's showing, is this:
I don't know what is the meaning of the error, since i'm trying to change the type to BOOLEAN and not TINYINT (i don't actually know if it's the same...)

im getting this error while creating fake factory model data in Laravel 8

\App\Models\Testt::factory()->create();
PHP Error: Class "Database\Factories\TesttFactory" not found in C:\xampp\htdocs\Project1\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php on line 683
im using cmd and using migrations to generate fake data
below is the mentioned code of factory, migrations
<?php
namespace Database\Factories;
use App\Models\Testt;
use Illuminate\Database\Eloquent\Factories\Factory;
**class TesttfactoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = \App\Models\Testt::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
//
];
}
}**
and for migrations the code is
**<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class CreateTesttsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('\App\Models\testts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->mediumText('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('testts');
}
}**

Mysql Database Migration Error in Laravel

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bogIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
$table->bogIncrements('id'); typo in here.

What is the best way to add dummy data into the "join table" in laravel?

I have two models with many to many relationship, and I did join them with a model with a third table.
What is the best way to insert dummy data into the third table without getting sql error for breaking constraints about foreign key chicks?
Is there a way to use the same data that already exists within the the first two tables?
I have these two tables:
class CreateLessonsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Lessons', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title', 100);
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Lessons');
}
}
The second:
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 50);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
and the "join" third table:
class CreateLessonTagsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('lesson_tags', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('lesson_id');
$table->unsignedBigInteger('tag_id');
$table->foreign('lesson_id')->references('id')->on('lessons')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('lesson_tags');
}
}
Thanks in advance
In the simple way
for($i =0;$i<100 ; $i++)
{
DB::table('lesson_tags')->insert(
[
'lesson_id' => Arr::random(DB::table('Lessons')->pluck('id')->toArray()),
'tag_id' => Arr::random(DB::table('tags')->pluck('id')->toArray())
]
);
}
You can use eloquent ORM like this
first you need to declare a relation in tag and lesson Models:
in Tag Model
public function lessons()
{
return $this->belongsToMany('App\Lesson');
}
in Lesson Model
public function tags()
{
return $this->belongsToMany('App\Tag');
}
then you can use this in loop for example
$Lesson = new Lesson();
$Lesson->user_id = ....
...
$Lessons->save();
$tag = new Tag();
$tag->name ='';
$Lessons->tags()->save($tag)
Efficiently, with three queries only:
$lessonIds = Lesson::pluck('id')->toArray();
$tagIds = Tag::pluck('id')->toArray();
$insert = [];
$relationsAmount = 10;
$now = \Carbon\Carbon::now();
for ($i = 0; $i < $relationsAmount; $i++) {
$insert[] = [
'lesson_id' => array_rand($lessonIds),
'tag_id' => array_rand($tagIds),
'created_at' => $now,
'updated_at' => $now,
];
}
\DB::table('lesson_tags')->insert($insert);
// if you name your pivot table per Eloquent naming convention (which would be 'lesson_tag' in this case), Laravel will do lot of things for you out of the box

Using UUID as default value in a laravel migration

I have the following migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateRatingGameUserAnswersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('rating_games_user_answers', function (Blueprint $table) {
$table->uuid('answer_token')->default(DB::raw('UUID()'));
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('rating_games_user_answers', function (Blueprint $table) {
$table->dropColumn('answer_token');
});
}
}
As you can see I'm trying to set UUID as default value. I've seen it here
But when I run php artisan migrate I see the following:
What is wrong?
As I came across this question when having the same issue:
With MySQL 8 you can use functions as default values. But you need to put paranthesis around them. So this works:
$table->uuid('uid')->default(DB::raw('(UUID())'));
But this won't be compatible with MySQL 5.7!
You cannot use mySQL function as default value it should be either set or you use a trigger.
try please like this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateRatingGameUserAnswersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('rating_games_user_answers', function (Blueprint $table) {
$uuid = DB::raw('select UUID()');
$table->uuid('answer_token')->default($uuid);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('rating_games_user_answers', function (Blueprint $table) {
$table->dropColumn('answer_token');
});
}
}