laravel many to may relationship - laravel

I have two tables passport and status and a pivot table passport_statuses.I have enter passport details and select status from dropdown but I am unable to save data in pivot table.please help.My codes are as below:
Passport model
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
Statuses model
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
PassportController
public function create()
{
$statuses=Statuses::lists('Status_Name','id');
return view('admin.passport.create')->with('statuses',$statuses);
}
public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('statuses'));
return redirect('admin/passport');
}
View
{!!Form::open(['url'=>'admin/passport'])!!}
<div class="form-goup">
{!!Form::label('Full_Name','Full Name')!!}
{!!Form::text('Full_Name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('Date_of_Birth','Date of Birth')!!}
{!! Form::input('date', 'Date_of_Birth', null, ['class' => 'form-control', 'placeholder' => 'Date']) !!}
</div>
{!!Form::label('Passport_Number','Passport Number')!!}
{!!Form::text('Passport_Number',null,['class'=>'form-control'])!!}
<div class="form-goup">
{!!Form::label('Status_Name','Status')!!}
{!!Form::select('Status_Name',$statuses,null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::submit('Add',['class'=>'btn btn-primary'])!!}
</div>
{!!Form::close()!!}

Your Passport model don't belongToMany statuses, but hasManyThrough statuses.
Maybe your problem is here.
I think the line in your model Passport.php should be like this :
public function status()
{
return $this->hasManyThrough('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
Check BelongToMany and HasMany documentation on laravel.com

class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","statuses_id", "passport_id")->withTimestamps();
}
}
belongsToMany relation takes third argument foreign key of current Model table and 4th parameter foreighn key of related model table
of course your table has to be like this passport_statuses with with at least two columns statuses_id and passport_id.And in your example with created_at and updated_at timestamp columns

I was able to solve this by changing input('statuses') to input('Status_Name') in PassportController
$passport->status()->attach($request->input('Status_Name'));

Related

How to Sharing or access a relations of intermediate model

I have a User Model
class User extends Authenticatable
{
public function banks() //this the relation to banks
{
return $this->belongsToMany(Bank ::class, 'customers', 'user_id', 'bank_id')
->withTimestamps();
}
}
and Bank model is
class Bank extends Model
{
public function customers()
{
return $this->belongsToMany(User::class, 'customers', 'bank_id', 'user_id')
->withPivot('name', 'phone', 'state');
}
}
the intermediate model is Customer
class Customer extends Model
{
use HasFactory;
protected $table = 'customers';
protected $fillable = [
//'id' this is the primary key
'bank_id',
'user_id',
'name',
'phone',
'state',
];
public function acounts()
{
return $this->hasMany(Account::class, 'customers_id');
}
}
the Account model is
class Account extends Model
{
use HasFactory;
protected $table = 'accounts';
protected $fillable = [
'customer_id', // this is a foriegin key to customers table
'currency_id',
'balance',
'state',
];
public function accountCurrency() // Accounts
{
return $this->belongsTo(Currency::class, 'currency_id');
}
}
the question is how can access to "acounts" relation from user "banks" what is the statment to link account relation with banks relation
$user = Auth::user();
in view
#foreach ($user->banks as $bnk)
<p class="lead">{{ $bnk->bank_name }} </p>
#foreach ($bnk->accounts as $ account)
<p class="lead">{{ $account->balance }} </p>
<p class="lead">{{ $account->accountCurrency->symbol }} </p>
#endforeach
#endforeach
I hope you help me
thanks
you can use hasManyThrough, check the documentation: https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

How to Show colors related to products using laravel?

I trying to show product color related to product I already have made a relation tables into database i just only want to know that when i click the specific product the color related to that product will be shown.thanks
I am facing error how to fix it ?
https://flareapp.io/share/VmeXLq5Q#F56
Does anybody have an idea ?
product_color model
class Product_color extends Model
{
public function products()
{
return $this->belongsToMany('App\Product', 'available_product_color', 'product_color_id',
'product_id');
}
}
product model
class Product extends Model
{
public function sizes()
{
return $this->belongsToMany('App\Product_sizes', 'available_product_sizes', 'product_id',
'product_size_id');
}
public function color()
{
return $this->belongsToMany('App\Product_color', 'available_product_color', 'product_id',
'product_color_id');
}
}
controller
public function single_product($product_slug)
{
$single_product = Product::with('sizes','color')->where('product_slug',$product_slug)->first();
return view('front_end/single_product',compact('single_product'));
}
}
HTML VIEW
<div class="form-group product__option">
<label class="product__option-label">Color</label>
<div class="input-radio-color">
<div class="input-radio-color__list">
#foreach($single_product->color as $color)
<span><img src="{{$color->color_image}}"></span>
#endforeach
</div>
</div>
</div>
I would highly suggest to stick to camel casing when it comes to naming your classes. Its a really good convention and helps. so ideally Product_color should be ProductColor or at least Product_Color. That also helps laravel to find the relevant information quite easily. As per laravel convention, your pivot table should be named in alphabetical order, so as the letter C comes before P, it should be called ColorProduct otherwise specify the name of table in the model
class Product_color extends Model
{
protected $table = 'available_product_color ??';
public function products()
{
return $this->belongsToMany(
'App\Product',
'available_product_color',
'product_color_id',
'product_id'
);
}
}
Here is the link to documentation. https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

Laravel Has Undefined Constant 'App\App\projects

I have created a model called company and projects, I need to show projects under a company. The company is showing fine, but when I added a project relation to the model, it displays an error. I am a newbie to Laravel.
Undefined constant 'App\App\projects' (View:
C:\xampp\htdocs\testdrive\resources\views\companies\show.blade.php)
C:\xampp\htdocs\testdrive\app\company.php
Model
use Illuminate\Database\Eloquent\Model;
class company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User);
}
public function projects()
{
return $this->hasMany(App\projects);
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<!-- Jumbotron -->
<div class="jumbotron">
<h1>{{$company->name}}</h1>
<p class="lead">{{$company->description}}</p>
</div>
<!-- Example row of columns -->
<div class="row">
#foreach($company->projects as $projects)
<div class="col-lg-4">
<h2>{{$projects->name}}</h2>
<p class="text-danger">{{$projects->description}} </p>
<p>
<a class="btn btn-primary" href="/projects/{{$projects->id}}" role="button">View Project</a>
</p>
</div>
#endforeach
</div>
</div>
#endsection
You've got a typo! namespaces should be strings:
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\projects');
}
You are missing class keyword in your model
class company extends Model
{
//
protected $fillable=[
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User::class);
}
public function projects()
{
return $this->hasMany(App\projects::class);
}
}
Hope this helps
Either pass class of the model or it's namespace within questions
public function user()
{
return $this->belongsTo(App\User::class); //or $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany(App\Project::class);
}
Aside from using quotes to reference the model as mentioned above.
It might also be necessary to define the namespace of your class.
Sidenote: it's also a Laravel naming convention to use PascalCase for classnames (ie. Company, WetCamel, FooBarClass)
namespace App\Company;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\Projects');
}
}
Use '' this to call the model.
Correct your syntax as:
public function projects()
{
return $this->hasMany('App\projects');
}

Laravel : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - Many to Many relationship

I know there's a bunch of problems asked about laravel integrity constraint violation, but none of them are Many to Many relationship, which is my case. Basically I have a table Hobi (hobby) and table Siswa (student), and the relationship is many to many since a student can have many hobbies and a hobby can be favored by many students. So here is the code :
This is my model Hobi :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Hobi extends Model
{
protected $table = 'hobi';
protected $fillable = [
'nama_hobi',
];
public function siswa(){
return $this->belongsToMany('App\Siswa', 'hobi_siswa', 'id_hobi', 'id_siswa');
}
}
model Siswa :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tgl_lahir',
'jns_klmin',
'id_kelas',
'id_hobi',
];
public function hobi(){
return $this->belongsToMany('App\Hobi', 'hobi_siswa', 'id_siswa', 'id_hobi')->withTimeStamps();
}
}
A piece of form view code which contained Hobi :
#if($errors->any())
<div class="form-group {{$errors->has('hobi') ? 'has-error' : 'has-success'}}">
#else
<div class="form-group">
#endif
{!! Form::label('hobi', 'Hobi:', ['class'=>'control-label']) !!}
#if(count($hobi_list) > 0)
#foreach($hobi_list as $key => $value)
<div class="checkbox">
<label>{!! Form::checkbox('hobi[]', $value, null) !!}{{$value}}</label>
</div>
#endforeach
#else
<p>Tidak ada pilihan hobi.</p>
#endif
</div>
And finally the controller :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Siswa;
use App\Telepon;
use App\Kelas;
use App\Hobi;
use Validator;
class SiswaCont extends Controller
{
public function siswa(){
$siswa_list = Siswa::orderBy('nama_siswa', 'asc')->paginate(10);
$jmlh_siswa = Siswa::count();
return view('siswa.ssw', compact('siswa_list', 'jmlh_siswa'));
}
public function create(){
$kelas_list = Kelas::lists('nama_kelas', 'id');
$hobi_list = Hobi::lists('nama_hobi', 'id');
return view('siswa.create', compact('kelas_list', 'hobi_list'));
}
public function store(Request $request){
$input = $request->all();
$validator = Validator::make($input, [
'nisn'=>'required|string|size:4|unique:siswa,nisn',
'nama_siswa'=>'required|string|max:30',
'tgl_lahir'=>'required|date',
'jns_klmin'=>'required|in:L,P',
no_telepon'=>'sometimes|numeric|digits_between:10,15|unique:telepon,no_telepon',
'id_kelas'=>'required',
]);
if ($validator->fails()) {
return redirect('siswa/create')->withInput()- >withErrors($validator);
}
$siswa = Siswa::create($input);
$siswa->hobi()->attach($request->input('hobi'));
return redirect('siswa');
}
}
I'm using pivot table hobi_siswa to contain id_siswa and id_hobi, creating a bridge. Hobi itself in form view is checkbox modeled. The problem is constraint, data Siswa for another column (nisn, nama_siswa, telepon, etc.) are saved, but Hobi not. Any help appreciated.
Use sync method instead of attach which accepts an array.
From the Docs
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table.
For example:
$user->roles()->sync([1, 2, 3]);

Access user's properties (with pivot table) laravel 5.1

I have a users table. The user has possibility to upload a post. The post is saved well to the database. The users can follow each other - so on a pivot table each follower_id has followees_id.
I need to get the posts of the current user followee's . I am kinda messed with getting it from a pivot table.
Here's my code so far:
controller:
protected function get_followee_posts($followee_posts) ////$followee_posts passed from the route.
{
$user = $this->user;
$user->followee()->attach($followee_posts);
$followee_posts = User::find($followee_posts);
}
view:
<div class="following_posts">
<p> Posts from people you're following: <p>
#foreach ($user->follower_id->followee_id->posts as $post)
<form action="/html/tags/html_form_tag_action.cfm" method="post">
<textarea name="comments" id="comments" style="width:96%;height:90px;background-color:white;color:black;border:none;padding:2%;font:22px/30px sans-serif;">
{!! $posts->full_post !!} </textarea>
</form>
#endforeach
route:
Route::get('hub/{followee_posts}','HubController#get_followee_posts')->name('followee_posts');
I am getting an error with the current code saying:
ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105:
Trying to get property of non-object
Any help would be lovely. Thank you.
Your not too specific about your schema, but this is how I would go about it.
User Model
class User extends Model
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
}
Follower Model
class Follower extends Model
{
protected $table = 'followers';
public function user()
{
return $this->belongs_to('User');
}
public function posts()
{
return $this->hasMany('Post', 'user_id', 'follower_id');
}
}
Post Model
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongs_to('User');
}
}
The followers table would look something like this:
user_id
follower_id
You could then use eloquent method chains to get the posts of a users followers:
// Get Users object with followers and followers posts
// We use with() to eager load relationships
$user = User::with('followers.posts')->find(2);
// Return associative array of post objects
$postsArray = $user->followers->lists('posts');
// Combine posts into a single collection
$posts = (new \Illuminate\Support\Collection($postsArray))->collapse()->toArray();
print_r($posts);

Resources