Laravel Pivot Table insert data - laravel

I have three tables.
I want to add a oyuncu (player) to a grup (group), so I created a method (public function oyuncustore(Request $request, $grup_id)).
But I get an error and I can't add rows to the pivot table.
Error:
ErrorException in BelongsToMany.php line 866: Argument 1 passed to
Illuminate\Database\Eloquent\Relations\BelongsToMany::formatSyncList()
must be of the type array, string given, called in
........./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
on line 831 and defined
Grup.php
class Grup extends Model
{
public function turnuva(){
return $this->belongsTo('App\Turnuva');
}
public function oyuncular(){
return $this->belongsToMany('App\Oyuncu');
}
}
Turnuva.php
class Turnuva extends Model
{
protected $table ='turnuvas';
public function grups(){
return $this->hasMany('App\Grup');
}
}
Oyuncu.php
class Oyuncu extends Model
{
protected $table ='oyuncular';
//$fillable = ['grup_id', 'oyuncu_id'];
public function grups(){
return $this->belongstoMany('App\Grup');
}
}
pivot table : grup_oyuncu created like that:
class CreateGrupOyuncuTable extends Migration
{
public function up()
{
Schema::create('grup_oyuncu', function (Blueprint $table) {
$table->increments('id');
$table->integer('oyuncu_id')->unsigned();
$table->foreign('oyuncu_id')->references('id')->on('oyuncular')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->integer('grup_id')->unsigned();
$table->foreign('grup_id')->references('id')->on('grups')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->engine = 'InnoDB';
});
}
public function down()
{
Schema::table('grup_oyuncu', function (Blueprint $table) {
//$table->dropForeign(['user_id']);
$table->dropForeign('grup_oyuncu_grup_id_foreign');
$table->dropForeign('grup_oyuncu_oyuncu_id_foreign');
});
Schema::drop('grup_oyuncu');
}
}
GrupController :
public function oyuncustore(Request $request, $grup_id)
{
$gr = new Grup;
$tumoyuncular = Oyuncu::All();
$grup= Grup::find($grup_id);
$gr->oyuncular()->sync($request->oyuncu, false);
$grpoyuncular = DB::table('grup_oyuncu')->select('oyuncu_id')->get();
Session::flash('success','Gruba oyuncu eklendi.');
return view('gruplar.show')->withGrup($grup)->withTumoyuncular($tumoyuncular)->withGrpoyuncular($grpoyuncular);
}
Form :
{!! Form::open(['route'=>['gruplar.oyuncustore',$grup->id],'method'=>'POST'])!!}
<h2>Yeni Oyuncu Ekle</h2>
{{Form::label('oyuncu','Oyuncu Adı Soyadı:')}}
<select class="form-control" name="oyuncu" id="">
#foreach($tumoyuncular as $toyuncu)
<option value="{{ $toyuncu->id}} ">{{$toyuncu->ad}} {{$toyuncu->soyad}}</option>
#endforeach
</select>
{{Form::submit('Oyuncu Ekle', array('class'=>'btn btn-success btn-lg btn-block', 'style'=>'margin-top:20px;'))}}
{!! Form::close()!!}
Maybe I created relationship with tables wrong?

Related

how can i handle the relations beetween products attributes and values?

i'm working on a Laravel/Livewire project
there are some products and services in this platform that user can order them.
the price of these products and services are changeable by their attributes . like size,color,quality and....
and i made a Many To Many relation between products and attributes.
but a can't handle it in my view where user should select that attributes before ordering
and my for each loop return wrong data . and i get this error :
Trying to get property 'pivot' of non-object .
my migration :
public function up()
{
Schema::create('attr_product', function (Blueprint $table) {
$table->foreignId('attr_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->string('value')->nullable();
$table->string('price')->nullable();
$table->timestamps();
});
}
product model :
public function attr(){
return $this->belongsToMany(Attr::class)->withPivot(['value','price'])->withTimestamps();
}
attr model:
public function product(){
return $this->belongsToMany(Product::class)->withPivot(['value','price'])->withTimestamps();
}
my controller :
class SingleProduct extends Component
{
public $product;
public function mount($id){
$this->product=Product::with('attr')->findOrFail($id);
}
public function render()
{
return view('livewire.front.product.single-product')->extends('layouts.Default')->section('content');
}
}
my loop in blade :
#foreach($product->attr as $attr)
<div class="col-lg-4 col-sm-6 mt-3">
<h6 class="mb-2 text-black">{{$attr->title}}</h6>
<select class="custom-select shadow-none">
#foreach($attr as $av)
<option value="{{$av->pivot->price}}">{{$av->pivot->value}}</option>
#endforeach
</select>
</div>
#endforeach
before #foreach add
#php
dd($product)
#endphp
You can troubleshoot your $product Model and relations
The right syntax for withPivot should be parameters separated by comma, try this:
product model
public function attr(){
return $this->belongsToMany(Attr::class)
->withPivot('value','price')
->withTimestamps();
}
attr model:
public function product(){
return $this->belongsToMany(Product::class)
->withPivot('value','price')
->withTimestamps();
}

Attempt to read property "file" on null

I keep getting the file on null error and can't seem to find why he can't locate the file?
#foreach($users as $user)
<tr>
<td>
<img height="62" src="{{asset($user->userdetail->file)}}" alt="">
</td>
</tr>
#endforeach
Userdetail Model
class UserDetail extends Model
{
use HasFactory;
protected $fillable = ['file'];
protected $uploads = '/img/avatar/';
public function getFileAttribute($userdetail){
return $this->uploads . $userdetail;
}
}
user model
protected $fillable = [
'name',
'is_active',
'email',
'photo_id',
'password',
];
public function userdetail(){
return $this->belongsTo(UserDetail::class);
}
Location of file
Migration userdetails
public function up()
{
Schema::create('user_details', function (Blueprint $table) {
$table->id();
$table->string('file');
$table->timestamps();
});
}
user
ddump of $user
You have to create the relationship for photo.
make this function in user model and place the name of the correct model
public function photo(){ return $this->hasOne(UserDetails::class, 'id', 'photo_id'); }
The problem was not the relation.
public function photo(){
return $this->belongsTo(UserDetail::class);
}
my problem was the name of the function i named it userdetail and then it will look for userdetail_id instead i needed it to name photo because then it will look for photo_id
Now it works!

How to get comments count of each post, in a list of posts that is in a User Dashboard in Laravel

Right now in the User Dashboard view (home.blade.php) it wrongly fetches the comments count of the first post by the user.
I would like to display the correct comments count of a post next to the posts' title.
What am I missing/doing wrong?
View (home.blade.php):
#if(count($posts) > 0)
<h5>Your Posts ({{ count($posts) }})</h5><hr>
#foreach($posts as $post)
<h6> {{ $post->title }}
{{ $comments_count }} comments </h6><hr>
#endforeach
#endif
Controller:
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
$post = Post::with('commentsCount')->first();
$comments_count = $post->commentsCount->first()->aggregate;
return view('home')->with('posts', $user->posts)
->with('comments_count', $comments_count);
}
}
Models (User, Post, Comment):
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function commentsCount()
{
return $this->comments()
->selectRaw('post_id, count(*) as aggregate')
->groupBy('post_id');
}
}
class Comment extends Model
{
protected $table = 'comments';
public $primaryKey = 'id';
public function post()
{
return $this->belongsTo('App\Post');
}
}
Migrations (CreatePostsTable, CreateCommentsTable):
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('title');
$table->mediumText('body');
$table->timestamps();
});
}
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('author');
$table->integer('post_id');
$table->integer('user_id');
$table->mediumText('comment');
$table->timestamps();
});
}
Your Post model hasMany comments, so you can able to use count() method, like : $post->comments->count() :
#if(count($posts) > 0)
<h5>Your Posts ({{ count($posts) }})</h5><hr>
#foreach($posts as $post)
<h6> {{ $post->title }}
{{ $post->comments->count() }} comments
</h6>
<hr>
#endforeach
#endif

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::save()

I want to insert data into multiple tables (one to one), but i get error and in my database the column "metode_id" is null. i want the "metode_id" is not null
this is class "Transaksi" :
class Transaksi extends Model
{
protected $table = "transaksi";
protected $primarykey = "id";
protected $fillable = ['stok_kedelai', 'stok_ragi', 'harga_kedelai', 'harga_ragi'];
public function metode()
{
return $this->belongsTo('App\Metode');
}
public function pengguna()
{
return $this->belongsTo('App\Pengguna');
}
}
This is class "Metode" :
class Metode extends Model
{
protected $table = "metode";
protected $primarykey = "id";
protected $fillable = ['bni', 'bri', 'mandiri', 'bca', 'btpn', 'ovo', 'gopay', 'dana'];
public function transaksi()
{
return $this->hasOne('App\Transaksi', 'metode_id');
}
}
This is database of "Transaksi" :
public function up()
{
Schema::create('transaksi', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('pengguna_id')->unsigned();
$table->integer('stok_kedelai');
$table->integer('stok_ragi');
$table->integer('harga_kedelai');
$table->integer('harga_ragi');
$table->bigInteger('metode_id')->unsigned();
$table->timestamps();
});
Schema::table('transaksi', function (Blueprint $table) {
$table->foreign('pengguna_id')->references('id')->on('pengguna')->onDelete('cascade')->onUpdate('cascade');
});
Schema::table('transaksi', function (Blueprint $table) {
$table->foreign('metode_id')->references('id')->on('metode')->onDelete('cascade')->onUpdate('cascade');
});
}
This is database of "Metode" :
public function up()
{
Schema::create('metode', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('bni')->nullable();
$table->integer('bri')->nullable();
$table->integer('mandiri')->nullable();
$table->integer('bca')->nullable();
$table->integer('btpn')->nullable();
$table->integer('ovo')->nullable();
$table->integer('gopay')->nullable();
$table->integer('dana')->nullable();
$table->timestamps();
});
}
i want insert data into mutiple table that which depends on the "id" of pengguna table but i get error Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::save()
public function data_penjualan(Request $request)
{
$pengguna = Pengguna::where('id', Auth::user()->id)->first();
$transaksi = new Transaksi();
$transaksi->stok_kedelai = $request->stok_kedelai;
$transaksi->stok_ragi = $request->stok_ragi;
$transaksi->harga_kedelai = $request->harga_kedelai;
$transaksi->harga_ragi = $request->harga_ragi;
$pengguna->transaksi()->save($transaksi);
$metode = new Metode();
$metode->bni = $request->bni;
$transaksi->metode()->save($metode);
return view('transaksi.supplier', compact('transaksi'));
}
this is my database, the "metode_id" get null, how i want that "metode_id" is not null :
enter image description here
If you try to update a belongsTo relationship, you have to use the associate method instead of save method.
...
$metode = new Metode();
$metode->bni = $request->bni;
$metode->save();
$transaksi->metode()->associate($metode);
$transaksi->save();
...
If you try to SaveMethod in the belongsTo relationship.
Add Comment(controller file)
public function addComment($id)
{
$comment = new Comment(['comment' =>'Comment 1']);
$user = User::find(1);
$user->comment()->save($comment);
return "Comment Submitted";
}
Comment.php (Model File)
class Comment extends Model
{
use HasFactory;
protected $table ="comments";
protected $fillable = ['comment'];
public function User()
{
return $this->belongsTo(User::class);
}
}
web.php (Route File)
Route::get('comment/{id}',[UserController::class,'addComment']);

How to make user, and roles relationship in Laravel 5

I have two tables :
User ->
id :
name :
role_id : ->references('id')->on('roles');
Roles ->
id :
role_name :
access :
I am trying to access roles details from user.
My User model has:
public function role()
{
return $this->belongsTo('App\Role');
}
My Role model has:
public function user()
{
return $this->hasMany('App\User');
}
When I try to do following :
$user = User::find(1);
$details = [
'name' => $user->first_name,
'role' => $user->role->role_name
];
I get error :
Trying to get property of non-object
My roles table contains access columns containing array of permissions to different routes. So my user will have only one role. While a role can have multiple users.
How to do that?
In my recent project, I handled these requirement in that way..
First of All Database Table Structure/Migration
User Table
class CreateUserTable extends Migration {
public function up() {
Schema::create('user', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('status')->default(0);
$table->boolean('is_admin')->default(0);
$table->boolean('notify')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
public function down() {
Schema::drop('user');
}
}
Role Table
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleTable extends Migration {
public function up()
{
Schema::create('role', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->boolean('status')->default(0);
$table->timestamps();
});
}
public function down()
{
Schema::drop('role');
}
}
Role And User Relation Table
class CreateRoleUserTable extends Migration {
public function up() {
// Create table for associating roles to users (Many-to-Many)
Schema::create('role_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('role')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id']);
});
}
public function down() {
Schema::drop('role_user');
}
}
After these table you have to handle permission by assigning to specific Role.
Permission
class Permission extends Migration {
public function up() {
Schema::create('permission', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('pattern');
$table->string('target');
$table->string('module');
$table->string('display_name')->nullable();
$table->boolean('status')->default(0);
$table->timestamps();
});
}
public function down() {
Schema::drop('permission');
}
}
Permission and Role Table Relation
class PermissionRole extends Migration {
public function up() {
// Create table for associating roles to permission (Many-to-Many)
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permission')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('role')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
}
public function down() {
Schema::drop('permission_role');
}
}
And Finally our model would look alike:
User Model
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'user';
protected $fillable = ['name', 'email', 'password', 'is_admin'];
protected $hidden = ['password', 'remember_token'];
public function scopeActive($query) {
return $query->whereStatus('1');
}
public function scopeAdmin($query) {
return $query->whereIsAdmin('1');
}
public function scopeNotify($query) {
return $query->whereNotify('1');
}
public function roles() {
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function attachRole($role) {
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->attach($role);
}
public function detachRole($role) {
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->detach($role);
}
public function attachRoles($roles) {
foreach ($roles as $role) {
$this->attachRole($role);
}
}
public function detachRoles($roles) {
foreach ($roles as $role) {
$this->detachRole($role);
}
}
public function isSuperUser() {
return (bool)$this->is_admin;
}
public function hasAccess($permissions, $all = true) {
if ($this->isSuperUser()) {
return true;
}
return $this->hasPermission($permissions, $all);
}
public function hasPermission($permissions) {
$mergedPermissions = $this->getMergedPermissions();
//dd($mergedPermissions);
if (!is_array($permissions)) {
$permissions = (array)$permissions;
}
foreach ($permissions as $permission) {
$matched = false;
// We will set a flag now for whether this permission was
// matched at all.
$founded_perms = find_in($mergedPermissions, "name", $permission);
if (!empty($founded_perms)) {
$matched = true;
}
}
if ($matched === false) {
return false;
}
return true;
}
public function getMergedPermissions() {
$permissions = array();
foreach ($this->getRoles() as $group) {
$permissions = array_merge($permissions, $group->permissions()->get()->toArray());
}
return $permissions;
}
public function getRoles() {
$roles = [];
if ($this->roles()) {
$roles = $this->roles()->get();
}
return $roles;
}
}
Role Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'role';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'display_name', 'description'];
public function scopeActive($query) {
return $query->whereStatus('1');
}
/**
* Many-to-Many relations with User.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users() {
return $this->belongsToMany('App\User');
}
public function permissions() {
return $this->belongsToMany("App\Permission");
}
}
Permission Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model {
protected $table = 'permission';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'pattern', 'target', 'module', 'display_name', 'status'];
public static function displayable() {
$prepared_array = [];
$temp = self::orderBy('module')->get()->toArray();
foreach ($temp as $sin) {
$prepared_array[$sin['module']][] = $sin;
}
return $prepared_array;
}
public function scopeActive($query) {
return $query->whereStatus('1');
}
public function roles() {
return $this->belongsToMany("App\Role");
}
}
Well, thats the basic structure helped to implement basic ACL and Auth with laravel 5.
Let me know if you have any further related question. Or If you need complete implementation I'll provide it to you.
For a one-to-many relationship you don't need a pivot table, so you can delete the user_roles table. Then add a role_id column to your users table, that will reference the id column in for your roles table. Next define the relations as follows for each of your models:
// User.php
public function role()
{
return $this->belongsTo('App\Role');
}
and
// Role.php
public function users()
{
return $this->hasMany('App\User');
}
Now you can access your role via the relation like this:
$user->role->name;
I got the problem, i was having a role column in user table, so when i was doing
$user->role->role_name
it was fetching role column instead of relationship.
i noticed you are not using the laravel default table naming conventions,
you are using user_roles whereass laravel naming conventions state you should use:
role_user (alphabetical and singular)
you could override the belongsToMany by stating your custom table name ofcource.
public function users() {
return $this->belongsToMany('App\User', 'user_roles');
}
on the second node there are also some good libraries to handle these kind of things, take a look at : https://github.com/romanbican/roles

Resources