Laravel Eloquent Migrate and Seed pivot table - laravel

I just started to learn Laravel and I have a problem with seeding the database with proper relationships.
I tried to create four tables which are: 'Users','Projekts','Posts','Projekt_User_Pivots'.
The idea is that every Projekt can have multiple users, every user can have multiple projekts and posts.
So I want to show only the posts within a project, from the users that belong to the project.
I tried to seed the database with seeders and factories but I can't achieve the relationship of primarykeys via the factories I want to use. In my solution I just need to run the seeding as often until it works what is realy dumb. I would appreciate some help.
Here are all Models:
Post.php:
<?php
namespace App\Models;
use App\Models\User;
use App\Models\Projekt;
use Illuminate\Database\Eloquent\Model;
use SebastianBergmann\CodeUnit\FunctionUnit;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Post extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
}
Projekt.php:
<?php
namespace App\Models;
use App\Models\Post;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Projekt extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function projektuserpivot()
{
return $this->hasMany(ProjektUserPivot::class);
}
}
ProjektUserPivot.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProjektUserPivot extends Model
{
use HasFactory;
protected $primaryKey = ['user_id', 'projekt_id'];
public $incrementing = false;
public function user()
{
return $this->belongsTo(User::class);
}
public function projekt()
{
return $this->belongsTo(Projekt::class);
}
}
User.php:
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
use App\Models\Projekt;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function post()
{
return $this->hasMany(Post::class);
}
public function projekt()
{
return $this->hasMany(Projekt::class);
}
public function projektuserpivot()
{
return $this->hasMany(ProjektUserPivot::class);
}
}
Here are all Factories:
PostFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Spatie\LaravelIgnition\Support\Composer\FakeComposer;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
*/
class PostFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'user_id' => $this->faker->numberBetween(0,999),
'title' => $this->faker->realTextBetween(10, 50),
'body' => $this->faker->realTextBetween(800, 1400),
];
}
}
ProjektFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Projekt>
*/
class ProjektFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => $this->faker->realTextBetween(10, 20),
'user_id' => $this->faker->numberBetween(1,999),
];
}
}
ProjektUserPivotFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ProjektUserPivot>
*/
class ProjektUserPivotFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'user_id' => $this->faker->numberBetween(1,999),
'projekt_id' => $this->faker->numberBetween(1,20),
];
}
}
UserFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
Here are all of the Migrations:
2014_10_12_000000_create_users_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->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('users');
}
};
2022_12_08_154030_create_projekts_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projekts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projekts');
}
};
2022_12_08_154042_create_posts_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
2022_12_09_114733_create_projekt_user_pivots_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projekt_user_pivots', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('projekt_id');
$table->primary(['user_id','projekt_id']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projekt_user_pivots');
}
};
Here are all Seeders:
DatabaseSeeder.php:
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\Post;
use App\Models\User;
use App\Models\Projekt;
use App\Models\ProjektUserPivot;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
User::factory(10)
->has(Post::factory()->count(10))
->has(Projekt::factory()->count(2))
->has(ProjektUserPivot::factory()->count(4))
->create();
}
}
PostSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
ProjektSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class ProjektSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
}
}
ProjektUserPivotSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class ProjektUserPivotSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
I know why the problem arises but how can I solve it?
Working migration and seeding
Not working migration and seeding

Laravel and its ORM Eloquent work better if you use exactly what they ask for: the pivot tabel between two table must be constructed as the following:
Schema::create('first_second', function(Blueprint $table)
{
$table->increments('id');
$table->integer('first_id');
$table->integer('second_id');
});
In your example, your pivot table is named projekt_user_pivot, and the ORM can't access it natively. Plus, Eloquent adds the automatic plural to the table, to it tries to find a table named projekt_user_pivots.
Add the $table->increments('id'); in the migration of your ProjektUser migration, and I suggest to follow Laravel's guidelines. You won't even need to create the model ProjektUser as Eloquent will do it itself.
~~
How to create your pivot table:
Make a migration (php artisan make:migration create_projekt_user_table)
function up() {
Schema::create('projekt_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('projekt_id');
$table->integer('user_id');
});
}
In your Models :
User.php
public function projekts()
{
$this->belongsToMany(User::class);
}
Projekt.php
public function users()
{
$this->belongsToMany(Projekt::class);
}
And your factories :
UserFactory.php
$projekts = Projekt::factory()->count(3)->create();
$user = User::factory()
->count(3)
->hasAttached($projekts)
->create();
This code will create 3 Users and 3 Projects, and all the Users will be linked to the 3 projekts in the pivot table, creating 9 lines.
With the definitions in the models that there is a many to many relationship between User and Projekt, your factory won't have any problem to populate itself the pivot table.
Note: if you ever need to add some additional data inside your pivot table (for example a role for the user for this specific project), you just have to update the migration to add the field, and you can define it with :
User.php
public function projekts()
{
$this->belongsToMany(User::class)->withPivot('role');
}
And you'll be able to access it in you code with :
foreach($user->projekts as $projekt)
{
echo $projekt->pivot->role;
}

Related

How can I fix User model in Laravel?

I have a custom User model in laravel. But I get errors when relationships with the User model. I couldn't find a similar problem on the internet. I have no idea what to do.
There was no User model before. I was using a model called Account and it was fine. But I updated the model name to User to use laravel's own Auth system.
Error:
Symfony\Component\ErrorHandler\Error\FatalError
Class Illuminate\Database\Eloquent\Relations\BelongsTo contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifierName, Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifier, Illuminate\Contracts\Auth\Authenticatable::getAuthPassword, ...)
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsTo.php:12
class BelongsTo extends Relation implements \Illuminate\Contracts\Auth\Authenticatable {
My User model
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Authenticatable {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'full_name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var string[]
*/
protected $hidden = [
'password',
];
/**
* Get the blog posts for the user.
* #return HasMany
*/
public function posts(): HasMany {
return $this->hasMany(BlogPost::class, 'id', 'author_id');
}
}
BlogPost model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BlogPost extends Model {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'author_id',
'thumbnail_id',
'title',
'slug',
'content',
'description',
'views',
];
/**
* Get the author for the blog post.
* #return BelongsTo
*/
public function author(): BelongsTo {
return $this->belongsTo(User::class, 'author_id', 'id');
}
}
users 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->id();
$table->string('full_name', 64);
$table->string('email', 64)->unique();
$table->string('password');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('users');
}
}
Try adding the Authorizable Trait to the User Model. Don't forget to add the use in too
use Illuminate\Foundation\Auth\Access\Authorizable;
class User extends Authenticatable
{
use Notifiable, Authorizable;

I have a belongs to relationship in laravel 8 and it returns null when I am trying to use that relationship in the tinker shell

I am using Laravel 8 and I have the following very simple models and migrations,
Author Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Author extends Model
{
use HasFactory;
public function profile()
{
return $this->hasOne('App\Models\Profile');
}
}
Profile Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
use HasFactory;
public function author()
{
$this->belongsTo('App\Models\Author');
}
}
create_authors_table migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuthorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('authors');
}
}
create_profiles_table migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('author_id')->unique();
$table->foreign('author_id')->references('id')->on('authors');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
Despite having the above models and migrations, if I create a new Profile model in tinker shell and do $profile->author() it returns null. I can not understand from where the problem is coming from.
(I tried changing $this->belongsTo('App\Models\Author'); to $this->belongsTo(Author::class); and $this->hasOne('App\Models\Profile'); to $this->hasOne(Profile::class); and restarting the tinker. The issue still persists. I even tried changing all the unsigned integer keys to unsigned big integers and the issue still persists.)
So I figured out the problem. The solution is simple, I have forgotten to add the all important return statement inside the author() method inside the Profile model.
It should be,
return $this->belongsTo('App\Models\Author'); instead of $this->belongsTo('App\Models\Author');
try with this one
return $this->belongsTo(Author::class, 'author_id', 'id');
instead of
$this->belongsTo('App\Models\Author');

Laravel Query Pivot Table with 3 Relation

I would appreciate in advance the help you could give me about the next problem that I can't solve.
I have 3 Tables
Contracts
Currencies
Amounts
and a Pivot Table
contract_currency_amount
Here I show you the migrations
Contracts
<?php
use Carbon\Carbon;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContractsTable extends Migration
{
/**
* Contracts Table
*
* #var string
*/
private $table = 'contracts';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('number')->unique();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
Currencies
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCurrenciesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('currencies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('abbreviation');
$table->string('description');
$table->boolean('active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('currencies');
}
}
Amounts
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAmountsTable extends Migration
{
/**
* Amounts Table
*
* #var string
*/
private $table = 'amounts';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
Contract_Currency_Amount Pivot Table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContractCurrencyAmountTable extends Migration
{
/**
* Pivot Table
*
* #var string
*/
private $table = 'contract_currency_amount';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('contract_id');
$table->unsignedInteger('currency_id');
$table->unsignedInteger('amount_id');
$table->timestamps();
$table->foreign('contract_id')
->references('id')->on('contracts')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')->on('currencies')
->onDelete('cascade');
$table->foreign('amount_id')
->references('id')->on('amounts')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
I have created the models for each of those tables, including a model for the pivot table, but I don't know how to make a query to the pivot table so that it returns all the data of a specific record, relating the 3 tables. for example I want in a view with Blade to go through a variable to show all the amounts, of a specific contract, and to be able to go through that variable in the following way:
#foreach($amounts as $amount)
{{ $amount->currency->abbreviation }}
#endforeach
I mean, I want the query to return the related values ​​of the 3 tables. I have no experience in the use of pivot tables, I would appreciate any help ..
EDIT 1
Amount Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Amount extends Model
{
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = ['amount'];
}
Currency Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Class Currency
*
* #property $id
* #property $abbreviation
* #property $description
* #property $active
* #property $created_at
* #property $updated_at
*
* #package App
* #mixin \Illuminate\Database\Eloquent\Builder
*/
class Currency extends Model
{
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = ['abbreviation','description','active'];
}
Contract model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Entity;
use App\Models\CInitiative;
class Contract extends Model
{
// TODO: This!
}
ContractCurrencyAmount Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ContractCurrencyAmount extends Pivot
{
protected $table = 'contract_currency_amount';
}
In order to achieve what you are looking for you must setup your models correctly. You must setup you ContractCurrencyAmount Model to be a normal eloquent model instead of extending pivot.
ContractCurrencyAmount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ContractCurrencyAmount extends Model
{
protected $table = 'contract_currency_amount';
public function contract()
{
return $this->belongsTo('App\Contract');
}
public function currency()
{
return $this->belongsTo('App\Currency');
}
public function amount()
{
return $this->belongsTo('App\Amount');
}
}
Contract
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'contract_id');
}
}
Currency
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'currency_id');
}
}
Amount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'amount_id');
}
}
Then you can do this:
foreach($amounts as $amount) {
{
foreach($amount->relations as $relation) {
$relation->currency->abbreviation;
}
}
You can also make use of eager loading to optimize your database queries:
$amounts = Amount::with('relations.currency')->get();
This will preload all the data you need in the for loops above, instead of querying the database on each iteration.

Unable to register user - photo_id does not have a default value (Version 5.6)

I have my users and photos tables create. Now that I added the photo_id into my users table, I am unable to register a user and it gives me an error saying that photo_id does not have a default value.
Here 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', 'email', 'password','photo_id'
];
public function photo(){
return $this->belongsTo('App\Photo');
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Photo Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
//
protected $fillable = ['path'];
}
Users Migration table
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('photo_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');
}
}
And here My photo migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhotosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('photos');
}
}
This is what I see when I try to register a user:

retrieve data from multiple table using ajax

this is posts table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->longText('status');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
this is comments table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->longText('comment');
$table->integer('like')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('comments');
}
}
this post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table='posts';
protected $fillable = ['status'];
protected $hidden = [];
public function profile(){
return $this->belongsTo('App\Profile', 'prf_id');
}
public function user(){
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
this is Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table='comments';
protected $fillable = ['comment','like'];
protected $hidden = [];
public function post(){
return $this->belongsTo('App\Post', 'post_id');
}
public function profile(){
return $this->belongsTo('App\Profile', 'prf_id');
}
public function user(){
return $this->belongsTo('App\User');
}
}
In blade page i can easilly retrieve all comments of a particular post like :
suppose i got $posts as post
#foreach ($post->comment as $comment)
{{$comment->comment}}
but in ajax how could i do this
suppose i return response()->json($posts);
any suggestion ?it will help me a lot
You don't have to write response()->json($posts), You can simply return $posts and Laravel will convert response to JSON automatically.
About Your exact problem: When querying $posts in controller, add with('comment') execution, like: $posts = Post::with('comment')->get() it will then return posts with comment prefetched.
It's Laravel's eager loading, You can read more about it here: https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

Resources