How to insert pivot table in case of many to many relation? (Laravel 5.3) - php

My form to add data is like this :
When klik save, It will call controller
My controller is like this :
public function store(Request $request)
{
$param = $request->only('account_name','account_number','bank_id','branch');
$result = $this->user_service->addUserBank($param);
if($result)
$status='success';
else
$status = 'failed';
return redirect('member/profile/setting/account')->with('status',$status);
}
My service is like this :
public function addUserBank($param)
{
$instance = User::where('id', '=', auth()->user()->id)->first();
$param['user_id'] = auth()->user()->id;
$param['status'] = 0;
$instance->banks()->attach([
'status' => $param['status'],
'account_name' => $param['account_name'],
'account_number' => $param['account_number'],
'branch' => $param['branch']
]);
return $result;
}
My model user is like this :
<?php
namespace App;
use App\Models\MasterData;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, FormAccessible;
protected $fillable = [
'name', 'email', 'password', 'api_token','birth_date','mobile_number','gender','full_name'
];
protected $hidden = [
'password', 'remember_token',
];
public function banks()
{
return $this->belongsToMany(MasterData::class, 'users_banks', 'user_id', 'bank_id') ->withPivot('status','account_name','account_number','branch')->withTimestamps();
}
}
So I have 3 table : users table, users_banks table (pivot table), and master_datas table
List of the names of the banks located in the master_datas table with type bank
Users table have field id, name, email, password etc => See model user
Master_datas table have field id (this is bank id), name (this is bank name), type (there exist type of bank, order status etc. So, get type = bank)
Users_banks table have field id, user_id, bank_id, status, account_name, account_number, branch
When run, it does not successfully insert into the pivot table (table users_banks).
It looks like my way to insert into the pivot table, not true.
Can you help me?
Additional
Table Master_datas is like this :

The problem is that you are not passing bank_id in your addUserBank() method. you can do it as:
public function addUserBank($param)
{
$param['status'] = 0;
auth()->user()
->banks()
->attach($param['bank_id'], array_only($param, ['status', 'account_name', 'account_number', 'branch']);
return true;
}
Note: You don't need to set user_id explicitly here as Laravel will automatically do it for you.
Docs

Create UserBank model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserBank extends model
{
protected $table = 'user_banks';
protected $fillable = ['user_id','bank_id'];
}
And then populate the table from controller:
public function store(Request $request)
{
$param = $request->only('account_name','account_number','bank_id','branch');
$result = $this->user_service->addUserBank($param);
if($result)
{
$pivot=new UserBank();
$pivot->user_id=auth()->user()->id;
$pivot->bank_id=$request->bank_id;
if($pivot->save())
{
$status='success';
}
}
else
{
$status = 'failed';
}
return redirect('member/profile/setting/account')->with('status',$status);
}

Related

How to retrieve a record from a parent table based on its id on a child table

I have two related models in a job listing application, Company and Listing. The relationship between them is that company may have listing and a listing must have exactly one company.
class Company extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'description',
'email',
'website',
'logo',
'address',
'city',
'state',
];
//Relationship to Listing
public function listings(){
return $this->hasMany(Listing::class, 'company_id');
}
//Relationship to company_image
public function company_image(){
return $this->hasMany(CompanyImage::class, 'company_id');
}
//Relationship to User
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
}
The listing model is defined as
class Listing extends Model
{
use HasFactory;
//Relationship to User
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
//Relationship to Company
public function company(){
return $this->belongsTo(Company::class, 'company_id');
}
I tried
public function edit(Listing $listing)
{
$cid = $listing->only(['id']); //to get the id of the company from the listings table
$cid = $cid['id'];
$comp = Company::orderby('name','Asc')->get(); // this list all company in a select field
$company = Company::whereHas('listings', function ($query) { //to get record of the company using the $cid from the listings table
$query->where('listings.id','=',$cid);
})->get();
dd($company); //to check the value returned.
// return view('listings.edit',[
// 'listing' => $listing,
// 'company' => $company,
// 'companys' => $comp
// ]);
}
i get an Undefined variable $cid when i use it like so where('listings.id','=',$cid).
i get null when i use it like so where('listings.id','=','$cid').
I want to get a result like
SELECT companies.name, companies.logo FROM companies join listings on listings.company_id = companies.id where listings.id = 4
which looks like:
enter image description here
You get the error because you need to pass the variable to closure.
You can pass the variable using use($variable) after function()
$company = Company::whereHas('listings', function ($query) use ($cid){
$query->where('listings.id','=',$cid);
})->get();
Just use your current code and access listing as below:
$some_id = 1;
$data = App\Models\Listing::find($some_id);
//For Name
$data->name;
//For images
$data->company->company_image;

How to create a relationship in laravel

Am new to laravel, I have issues trying to connect this tables: plans,users and loans even after reading the docs,
I have a plans tables that have all my plans, then I have a users table and loans table, my loans table has a user_id and a plan_id, all I want is to pull the records for plans and the users in the loan model.
Loanplan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
//
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->belongsTo('App\loan');
}
}
my loan model:
Loan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
I want get all the loan plans and users table records with plan_id and user_id as foreign respectively respectively in my LoanController.
I think the problem is with the customization of the loans table name in the Loanplan model.
According with your descriptions you need the followings setup:
A User can access to one or many Loans
users 1---m plans
A Loan belongs to a Loanplan // here I'm using Loanplan because that is your model name.
loans 1---m plans
So, this means:
User.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
Loan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
//
];
public function user()
{
return $this->belongsTo(User::class);
}
public function plan()
{
// Notice that here I'm specifying the foreign key:
return $this->belongsTo(Loanplan::class);
}
//
}
Loanplan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
So with this, you can access the information in your LoanController.php:
LoanController.php
public function myCoolMethod()
{
// get a user
$user = User::first();
// access his/her loans
$loans = user->loans;
//
// get a loan plan
$plan = Loanplan::first();
// access its loans
$loans = plan->loans;
//
}
I strongly suggest you to read the Laravel Documentation regarding relationships and also a course for database design. Have a good day mate.
Loanplan.php is missing the protected $table = "plans" variable
Same file,
public function loan()
{
return $this->belongsTo('App\loan');
}
the relationship should be hasOne or hasMany, not belongsTo.
Moreover, the name of the class should have Loan with capital L.
public function loan()
{
return $this->...('App\Loan');
}
First of all add protected $table = 'plans'; to your Loanplan model since the table name is 'plans'
Loanplan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->hasOne('App\loan'); // or hasMany
}
}
?>
Loan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
?>
add this to the User Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function Loan()
{
return $this->hasOne('App\Loan'); // or hasMany
}
}
?>
First, you have to check if the model already querying from table that you created before. Laravel will automatically access table base on your class name.
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
You can read it from this documentation
Second, make sure you call the right class. From Loanplan.php in the loan() method it's not using uppercase for the first letter.
Third, try to state the foreign key and primary key. You can also check how to do it in the documentation.

Cannot make it work to get many to many related table by custom pivot table in laravel5.6

My Post model has this function not working
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = "wp_posts";
protected $primaryKey = "ID";
public function taxonomies()
{
return $this->belongsToMany('App\Models\TermTaxonomy', 'wp_term_relationships', 'object_id', 'term_taxonomy_id');
}
}
I wanna get the taxonomies data from post through pivot table but I can't.
I connected Laravel to my WP database and tried to get Taxonomies from Posts.
Posts and Taxonomies are many to many relationship with 'wp_term_relationships' pivot table.
post table has 'ID' primary key
taxonomy table has 'term_taxonomy_id' primary key
The pivot table is like
'wp_term_relationships'
- 'object_id' ... related to Post.ID
- 'term_taxonomy_id' ... related to Taxonomy.term_taxonomy_id
I don't know why this not working. If anyone knows plz help me. Thank you so much.
Add
// Taxonomy
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TermTaxonomy extends Model
{
protected $table = 'wp_term_taxonomy';
protected $primaryKey = 'term_taxonomy_id';
}
// in the Controller
public function profile($id)
{
$teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
$query->where('post_type', 'answer')->take(3);
}])->firstOrFail();
$data = [
'teacher' => $teacher
];
return view('teacher.profile', $data);
}
// in the View
#foreach($teacher->posts as $answer)
#php
foreach($answer->postParent->taxonomies as $taxonomy) {
print($taxonomy->term_id);
}
#endphp
#endforeach
The actual problem was not how to define many to many relationship,
it was how to retreive the relation data.
public function profile($id)
{
$teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
$query->where('post_type', 'answer')->take(3)->with(['postParent' => function ($query) {
$query->where('post_type', 'question')->with(['taxonomies' => function ($query) {
$query->where('taxonomy', 'question_category')->with(['term']);
}]);
}]);
}])->firstOrFail();
$data = [
'teacher' => $teacher
];
return view('teacher.profile', $data);
}

Save object with foreign keys in laravel

I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.

How can i fetch another table data in different table column?

Firstly i have given all three table structure.
actions table:
roles table:
permissions table:
Here how can i get action_id in permissions table from actions table?
and how can i get role_id in permissions table from roles table? Please tell me the easy way to do , i am beginner in Laravel.
Action Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Action extends Model
{
//
protected $table = "actions";
//public $fillable = []
public function role(){
return $this->belongsTo('App\Action');
}
public function permission(){
return $this->belongsTo('App\Action');
}
}
Permission Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
//
protected $table ="permissions";
public function actionGet(){
return $this->hasOne('App/Permission');
}
}
update permission_table a join action_table b on a.id = b.id join roles_table c
on a.id = c.id
set a.action_id = b.id,
a.role_id = c.id;
This will update action_id in permission table with id from action table
also, role_id in permission table with id from role table.
I assume this is what you want.
I have found a way to do this work.I am using for this Query Builder to insert actions table id in permissions table action_id column.
For this, in RoleController:
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('permissions')->insert([
'role_id' => $id
]);
return redirect(route('allRole'));
}
And ActionController:
public function store(Request $request)
{
//
$action= [];
$action['action'] = $request->input('action');
$data= Action::create($action);
$id= $data->id;
DB::table('permissions')->insert([
'action_id' => $id
]);
return redirect(route('allAction'));
}
Before do this add use DB; in your header of each controller.
Hope this will help for someone.

Categories