Laravel 'many to many' user associates with many posts? - laravel

In PostsController
public function store()
{
$this->validate(request(), [
'title' => 'required',
'body' => 'required'
]);
auth()->user()->publish(
new Post(request(['title', 'body']))
);
return redirect('/');
}
in user.php
public function posts()
{
return $this->belongsToMany(Post::class);
}
public function publish(Post $post)
{
$this->posts()->save($post);
}
the thing is after login I am seeing the all posts associate with only logged in user but i want many posts to many user relation

The user model must be like this
class User extends Authenticatable
{
public function Posts()
{
return $this->belongsToMany('App\Post');
}
}
The post model must be like this.
class Post extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
The migration class for user
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');
}
}
The migration class for Post
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Also u need a pivot table. The table name must be - user_post
class CreatePostUser extends Migration
{
/**
* Run the migrations.
*
* #return void
* user_post
*/
public function up()
{
Schema::create('post_user', function(Blueprint $table)
{
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
$table->integer('post_id')->unsigned()->nullable();
$table->foreign('post_id')->references('id')
->on('posts')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_post');
}
}
Please refer this link for more details - https://laravel.com/docs/5.5/eloquent-relationships#many-to-many
I hope you find this useful!

Related

Laravel Eloquent Migrate and Seed pivot table

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;
}

Laravel 6 Migration problem: Foreign Key Constraint is incorrectly formed

I know this question has been asked a lot and I have tried all the answers, I just can't seem to debug this problem I am having.
I have a migration called create_product_image_table
class CreateProductImageTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_image', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('product_id');
$table->string('image_url');
$table->timestamps();
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product_image');
}
}
The other migration called create_products_table
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('product_name');
$table->text('product_description');
$table->decimal('product_cost', 8, 2);
$table->decimal('product_price', 8, 2);
$table->bigInteger('unit_sold')->nullable();
$table->bigInteger('UPC')->nullable();
$table->unsignedBigInteger('product_image_id')->nullable();
$table->timestamps();
$table->foreign('product_image_id')
->references('id')
->on('product_image')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
They both have the same unsigned big integer type. After changing the date when the migration was created and deleted the table and later the database itself, I just can't seem to pass Errno 150 error.
Thanks for your help.
Thomas
Your products_table has a relationship with product_image_table,
And product_image_table belongs to products_table.
So you need to define the relation only on product_image_table.
You need to create products_tablefirst, and it will look like :
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('product_name');
$table->text('product_description');
$table->decimal('product_cost', 8, 2);
$table->decimal('product_price', 8, 2);
$table->bigInteger('unit_sold')->nullable();
$table->bigInteger('UPC')->nullable();
$table->unsignedBigInteger('product_image_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Then you need to create product_image_table, which will look like :
class CreateProductImageTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_image', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('product_id');
$table->string('image_url');
$table->timestamps();
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product_image');
}
}
Adde default string length in your AppServiceProvider
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
}

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