I have these relations in my database
Schema::create('my_users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('fullName');
$table->string('userName');
$table->string('password');
$table->string('photo');
$table->string('email');
});
and
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('photo');
$table->text('caption');
$table->integer('like');
$table->integer('my_user_id');
});
my models :
class myUser extends Model
{
public function post()
{
return $this->hasMany('App\post');
}
}
class post extends Model
{
public function user()
{
return $this->belongsTo('App\myUser');
}
}
now I'm trying to get a user's data using the following code :
$post = post::find(1);
$user = $post->user;
but it doesn't work and $user is NULL.
I'm sure that in posts table there is a record with id 1.
the weird part is this that I get no error when I change the method's name like this :
$post = post::find(1);
$user = $post->somethingBullshit;
I'm using laravel 5.3.
help please.
Confirm that you are naming your class files starting with upper case letters, and modify your class declarations accordingly, such as:
class MyUser extends Model
{
public function post()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\MyUser');
}
}
You can then select the user when you obtain the post by utilizing eloquent's with() method, and obtain your $user variable from your $post variable, OR just use the user property of post as follows:
$post = Post::with('user')->find(1);
$user = $post->user;
Related
I want to return the projects of the authenticated user, but am not getting any. I know the records exist in the database.
This is my model Project:
public function users(){
return $this->hasMany(User::class);
}
this is my model User:
public function projects(){
return $this->hasMany(Projet::class,'user_id');
}
and this is the controller function :
public function projetuser(){
$user = User::find(auth()->user()->id);
return $user->projects;
}
and this my user_projet migration:
public function up()
{
Schema::create('user_projet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('projet_id');
$table->foreign('projet_id')->references('id')->on('projets')->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('membre')->nullbale();
$table->timestamps();
});
}
You are defining a many-to-many relationship incorrectly. Use belongsToMany() instead of hasMany(). Because your pivot table name is not standard (it should be alphabetic order projet_user) you need to include it in the relationship definition as well.
<?php
use Illuminate\Database\Eloquent\Model;
class Projet extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'user_projet');
}
}
class User extends Model
{
public function projets(){
return $this->belongsToMany(Projet::class, 'user_projet');
}
}
Now in your controller you can do this:
public function projetuser(){
return auth()->user->projets;
}
Your question seems to vary between "projet" and "project." I assumed "projet" was the correct spelling, but try to keep this consistent.
Please note also the typo in your migration: nullbale.
I'm trying to give ability on user to see his orders. I have created relationships but when i (dd) the result of the function, the related model attributes are empty.
I don't know what is wrong.
Here is my buyer function
//Buyer Orders
public function myOrders()
{
$user = User::find(auth()->user()->id);
$user = $user->products();
dd($user);// related model attributes shows empty
return view('myOrders')->with(compact('user'));
}
and here is my user
public function products()
{
return $this->hasMany(Products_model::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function allOrdersBuyerSeller()
{
return $this->hasMany(OrderProduct::class);
}
products_model
public function orders()
{
return $this->belongsToMany('App\Order', 'order_product');
}
public function user()
{
return $this->belongsTo('App\User');
}
User Migration
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Product Migration
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('pro_name');
$table->integer('pro_price');
$table->text('pro_info');
$table->integer('stock');
$table->integer('category_id');
$table->string('image')->nullable();
$table->timestamps();
$table->bigInteger('seller_id')->unsigned()->index();
$table->foreign('seller_id')->references('id')->on('users')->onDelete('cascade');
});
}
I would like to see the attributes of the table like price, name, info, img and etc.
Barring the comments about your code, the reason you're not seeing the result of your products query is that you're not passing a closure to the query.
$user = $user->products();
Currently, $user is a QueryBuilder instance. Until you use a closure, like first(), get(), paginate(), etc, you won't be able to see the rows. Modify your code to the following:
$products = $user->products;
// OR
$products = $user->products()->get();
If you omit the (), it will load the relationship using products()->get(), unless already loaded.
Edit: You likely need to include foreign keys to your relationships as the Model name won't match:
User.php
public function products(){
return $this->hasMany(Product_model::class, "seller_id", "id");
}
Probably best to review the contents of the documentation for Relationships; https://laravel.com/docs/5.8/eloquent-relationships. There's a lot of incorrect practices going on with your naming, querying, etc.
The following code in tinker returns a null value while it should return the project to which the first task is linked.
App\Task::first()->projects;
Already tried renaming the method names, column names in migrations, tried exiting tinker and logging back in
Project Migration
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('title');
$table->string('description');
$table->timestamps();
});
}
Task Migration
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('project_id');
$table->string('description');
$table->boolean('completed')->default(false);
$table->timestamps();
});
}
Project.php
use App\Task;
class Project extends Model
{
protected $fillable = ['title','description'];
public function tasks(){
return $this->hasMany(Task::class);
}
}
Task.php
use App\Project;
class Task extends Model
{
protected $fillable = [
'completed'
];
public function projects(){
return $this->belongsTo(Project::class);
}
}
If anyone could just review this piece of code and let me know where I have made any conventional\idiotic mistakes (since Im new to route model binding) it would be of great help!
A task belongs to a project, so rename projects to project as it is singular. If you keep projects then provide the column name as second parameter:
public function projects(){
return $this->belongsTo(Project::class, 'project_id');
}
// I suggest this
public function project(){
return $this->belongsTo(Project::class);
}
Your column types are different, for the id of the project you use Big Integer and for the reference you use Integer, so this:
$table->unsignedInteger('project_id');
should be this:
$table->unsignedBigInteger('project_id');
// also good to make the relationship on the Database level:
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
Not sure what im doing wrong but im getting this error, and im not sure how to solve it.
i referenced this, but im still unsure, maybe its my schema migration
im using laravel 5.5
laravel 5.2 Call to undefined method Illuminate\Database\Query\Builder::associate()
Call to undefined method
Illuminate\Database\Query\Builder::withTrashed()
PostController.php
public function isLikedByMe($id)
{
$post = Post::findOrFail($id)->first();
if (Like::whereUserId(auth()->id())->wherePostId($post->id)->exists()){
return 'true';
}
return 'false';
}
public function like(Post $post)
{
$existing_like = Like::withTrashed()->wherePostId($post->id)->whereUserId(auth()->id())->first();
if (is_null($existing_like)) {
Like::create([
'post_id' => $post->id,
'user_id' => auth()->id()
]);
} else {
if (is_null($existing_like->deleted_at)) {
$existing_like->delete();
} else {
$existing_like->restore();
}
}
Likes Model
class Like extends Model
{
//
}
User model condensed to whats important
public function likes()
{
return $this->belongsToMany('App\Post', 'likes', 'user_id', 'post_id');
}
Post model
public function likes()
{
return $this->belongsToMany('App\User', 'likes');
}
Migration:
likes migration
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
});
}
Posts migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Your Eloquent model should use the Illuminate\Database\Eloquent\SoftDeletes trait to make use of the withTrashed() method.
Like::class
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Like extends Model
{
use SoftDeletes;
}
Had the same issue, the problem was that I used DB::table($table_name) instead of calling the model, using the model helped.
Regards
I seem to be having a problem understanding this hierarchical relationship.
Farm > Fields > Shepherds > Sheep
It seems a pretty straightforward hierarchy - Farm hasMany fields, field hasMany shepherds, shepherd hasMany sheep.
Sheep belong to a shepherd, shepherds belongs to fields, fields belong to farms.
I have defined this model relationships thus:
class Sheep extends Model {
protected $fillable ['name'];
public function shepherd() {
return $this->belongsTo('App\Shepherd');
}
}
class Shepherd extends Model {
protected $fillable ['name'];
public function field() {
return $this->belongsTo('App\Field');
}
public function sheep() {
return $this->hasMany('App\Sheep');
}
}
class Field extends Model {
protected $fillable ['name'];
public function farm() {
return $this->belongsTo('App\Farm');
}
public function shepherd() {
return $this->hasMany('App\Shepperd');
}
}
class Farm extends Model {
protected $fillable ['name'];
public function field() {
return $this->hasMany('App\Field');
}
}
public function up()
{
Schema::create('farms', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
}
public function up()
{
Schema::create('fields', function (Blueprint $table) {
$table->increments('id');
$table->integer('farm_id');
$table->string('name');
});
}
public function up()
Schema::create('shepherds', function (Blueprint $table) {
$table->increments('id');
$table->integer('field_id');
$table->string('name');
});
}
public function up()
Schema::create('sheep', function (Blueprint $table) {
$table->increments('id');
$table->integer('shepherd_id');
$table->string('name');
});
}
I would expect to be able to save each model in the following manner.
$farm = new App\Farm;
$farm->name = 'West Farm';
$field = new App\Field;
$field->name = 'The orchard';
$shepherd = new App\Shepherd;
$shepherd->name = 'Jason';
$sheep = new App\Sheep;
$sheep->name = 'Sean';
$farm->save();
$farm->field()->save($farm);
$farm->field->shepherd()->save($shepherd);
$farm->field->shepherd->sheep()->save($sheep);
But it does not work. Once I get to $farm->field->shepherd()->save($shepherd); the process breaks down. I would appreciate some assistance in the correct manner of saving using the relationships between all the tables.
I'm pulling my hair out trying to understand this, so any help would be greatly appreciated.
thanks
Your code breaks here:
$farm->field->shepherd()->save($shepherd);
Farms have many fields, so when you reference $farm->field, you're getting a collection of Field object, not just a single Field object.
To make it work, you need to either reference $farm->field[0]
$farm->field[0]->shepherd()->save($shepherd);
or just use the $field object you created before:
$field->shepherd()->save($shepherd);
I'd also suggest to use plural names for your hasMany relations (fields, sheeps, etc.) - this way you'll always remember that the referenced fields refer to a collection, not a single object