how can i get around this belongsToMany pivot error - laravel

i have the following relationship for a belongsToMany relationship
Table:| users | forums |forum_user (pivot table)
| id | id | id
| name | name | user_id
| email | | forum_id
| | |
and have defined the following relationships
pubic function forums() {
return $this->belongsToMany(Forum::class);
}
on the user model and
pubic function forums() {
return $this->belongsToMany(Forum::class);
}
on the forum model
now when i try to do this
User::first()->forums()->get()
it returns the error
Symfony\Component\Debug\Exception\FatalErrorException
Type of Illuminate\Database\Eloquent\Relations\Pivot::$ must be array (as in class
Illuminate\Database\Eloquent\Model)
how can i get around this error
i'm currently using laravel 6 in my project

try this:
User::first()->forums->get();
And maybe rewrite the relation on User model to:
return $this->belongsToMany(Forum::class, 'forum_user', 'user_id', 'forum_id');

On the forum model shouldnt relation reflect user?
pubic function forums() {
return $this->belongsToMany(Forum::class);
}
Shouldnt this be
pubic function users() {
return $this->belongsToMany(User::class);
}

Related

Laravel Route Model Binding Return False Owner of The Post

Good morning/afternoon/evening!
I have 2 model, User and post
User.php
public function getRouteKeyName()
{
return 'user_name';
}
public function posts()
{
return $this->hasMany(Post::class, 'by_id', 'id');
}
I have two records in users table
|--------------------------------------------|
| id | user_name | ... | ... |
|--------------------------------------------|
| 1 | megamanx | ... | ... |
| 2 | black_zero | ... | ... | // Edited
Post.php
public function getRouteKeyName()
{
return 'slug';
}
public function by()
{
return $this->belongsTo(User::class, 'by_id', 'id');
}
I have one record in posts table
|----------------------------------------------------|
| id | by_id | slug | ... |
|----------------------------------------------------|
| 1 | 1 | test-first-post | ... |
In my route
Route::group(['prefix' => '{user}', function () {
Route::get('/', function (User $user) {
return View::make('user.index', compact('user'));
});
Route::get('/{post}', function (User $user, Post $post) {
return View::make('post.index', compact('user', 'post'));
});
});
As you can see I use Route model binding for User user_name and for Post slug
So when I visit the route, ex :
127.0.0.1:8000/megamanx/test-first-post
// it return the correct owner
user megamanx is the owner of the post (test-first-post)
But, when I try the user param to other user, ex :
127.0.0.1:8000/black_zero/test-first-post
// Hey you don't own that post!
And the owner post name change to black_zero, but he didn't own that post
So how to solve this? I want when the user try to change the user_name, to something else, return 404. because only user megamanx own post test-first-post
I'm always open to critics, cause I want to be a better developer, if there's any wrong in method above (Route, model, etc), please correct me!, thank you (・∀・)ノ
Sorry for bad english ( ̄▽ ̄*)ゞ
Thanks in advance!

hasOneThrough Laravel Eloquent Relationship

I have 3 tabes categories, sub_categories & products
category table
---------------------
| id | category_name |
---------------------
sub_category table
--------------------------------------------
| id | category_id(FK) | sub_category_name |
--------------------------------------------
product table
-----------------------------------------------------------------
| id | sub_category_id(FK) | product_name | product_description |
-----------------------------------------------------------------
**How do I get product category name using hasOneThrough eloquent relationship ( or using any other relationship).
I tried this in product model **
public function category(){
return $this->hasOneThrough(
Category::class,
SubCategory::class
);
}
But it gives error: Unknown column 'sub_categories.product_id'
You can install this external package staudenmeir/belongs-to-through to add the relationship you need.
class Product extends Model
{
public function subCategory()
{
return $this->belongsTo(SubCategory::class);
}
public functoin category()
{
return $this->belongsToThrough(Category::class, SubCategory::class);
}
}
class SubCategory extends Model
{
public functoin category()
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
public function subCategories()
{
return $this->hasMany(SubCategory::class);
}
public functoin products()
{
return $this->hasManyThrough(Product::class, SubCategory::class);
}
}
If you need to access Category directly from Product, and want to use laravels functions like $product->category()->attach($category->id) etc, then you need this dependency to achieve that.
If you are ok with doing:
$product->subCategory->category;
// or
$product->subCategory->category()->attach($category->id);
Then you don't need the dependency and you can exclude the category relationship on the Product model.

How to GroupBy in Relationship?

I have post table
| ID | TITLE | SLUG | CONTENT | COMMENTS_COUNT |
and i have post_reactions table
| ID | USER_ID | TYPE | POST_ID |
I want to make a relationship that what reactions that post have
You can directly do it by model.
public function postrelation()
{
return $this->hasMany(PostRelation::class)->groupBy('type');
}
Or
Post::with(['postrelation' => function($q){
$q->groupBy('type');
}])->get();
You can use callback function for grouping your relations describe at below.
Post::with(['post_reactions' => function($query){
$query->groupBy('TYPE');
}])->get();
You can make relation with the help of follwing syntax in the Model Class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
/**
* Get the phone record associated with the user.
*/
public function phone(){
return $this->hasOne('App\Phone');
}
}

Override primary key with foreign key in hasMany relation using laravel

Here are my tables
Posts
id | name | created_At
Comments
id | comment | post_id | created_at
Post Model
function comments(){
return $this->hasMany('App\Models\Comment','id','post_id');
}
PostsController
function index()
{
Post::with('comments')::get();
}
Now how can i get list of all posts along with comments?
I am trying to match post_id in the child table.
In Your Post Model:
public function comments()
{
return $this->hasMany('App\Model\Comment');
}
In Your Post Controller :
use Illuminate\Http\Request;
function index(Request $request)
{
$posts=Post::with('comments')->get();
// in json
return response()->json($posts);
// in your view
//return view('viewname')->with('posts',$posts);
}

Laravel 4.2.8 > many to many > create a new related model and attach > error

don´t get it why this error occurs when inserting a new zip-code and relate it to an existing company using laravels eloquent belongsToMany feature.
here is my setup:
Error
file: "...\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php"
line: 411
message: "postcode"
type: "Illuminate\Database\Eloquent\MassAssignmentException"
Insertcode
$postcode = new Postcode(array('postcode' => $data['plz']));
Company::find($data['id'])->postcodes()->save($postcode);
Company Model
class Company extends Eloquent {
public function postcodes()
{
return $this->belongsToMany('Postcode');
}
}
Postcode Model
class Postcode extends Eloquent {
public function companies()
{
return $this->belongsToMany('Company');
}
}
Table postcodes
| id | postcode |
Table company_postcode
| id | postcode_id | company_id |
Table companies
| id | name |
Does anybody know why this isn´t working?
The error says
MassAssignmentException
That is because you are trying to mass assign postcode
new Postcode(array('postcode' => $data['plz']));
So make sure you whitelist the postcode variable as being mass assignable
class Company extends Eloquent {
protected $fillable = array('postcode');
public function postcodes()
{
return $this->belongsToMany('Postcode');
}
}

Resources