How to connect foreign-key on 3 tables relation - laravel

I dont know how to create a great title , iam sorry . so
i have 3 table . USER , SPECIAL_USER, EDUCATION_SPECIAL_USER
in USER i have data basic like
id ,name , address , email ,etc
in SPECIAL_USER data
id , user_id , height , weight
in EDUCATION_SPECIAL_USER i have
id , special_user_id , name_school , skills , etc
i have table LIKE on this table . i have problem how to call EDUCATION_SPECIAL_USER based on id on USER . its have problem because my EDUCATION_SPECIAL_USER is not have relation directly on USER table .
its my controller , how to solve this
public function PDF_profile(Request $request,$id){
$users = User::findOrFail($id);
$special_users= Special_Users::where('user_id',$id)->first();
$EDUCATION_SPECIAL_USER= EDUCATION_SPECIAL_USER::where('Special_user_id',$id)->get();
$pdf = PDF::loadView('admin.pdf_profile',
[
'EDUCATION_SPECIAL_USER '=>$EDUCATION_SPECIAL_USER ,
'users' => $users,
'special_users'=> $special_users,
]);
dd($r_kgb);
//return $pdf->stream('Profile.pdf')->header('Content-Type','application/pdf');
}
this data is not out because this wrong id , how i can solve this ?

You can use "has-many-through" relationship:
// In your model User:
public function educationSpecialUsers()
{
return $this->hasManyThrough(EducationSpecialUser::class, SpecialUser::class);
}
// then use:
$user = User::findOrFail($id);
$educationSpecialUsers = $user->educationSpecialUsers;
hope helpful.

Related

How to catch 1 colomn (id) on table in edit form

I have 1 table data . and I have function edit on this table . in this edit form I have select dropdown to show pluck from database .
I have 3 table . this name is aduan, ipsrs , teknisi
struckture aduan table
id
user_id
ipsrs_id
teknisi_id
aduan
etc.....
ipsrs table
id
nama_bagian
etc....
teknisi table
id
ipsrs_id
nama_teknisi
etc...
This is my controller :
public function index(Request $request)
{
$ipsrs = DB::table('ipsrs')->pluck('nama_bagian','id');
$belum_kerjakan = Aduan::with('users')->where('status','Belum Dikerjakan')->get();
$teknisi = Teknisi::where('ipsrs_id' , 1)->pluck('nama_teknisi', 'id');
$dalam_proses = Aduan::with('users')->where('status','Sedang Dikerjakan')->get();
$selesai = Aduan::with('users')->where('status','Selesai')->get();
return view('admin.admin_dashboard',[
'belum_dikerjakan' => $belum_kerjakan,
'dalam_proses' => $dalam_proses,
'selesai' => $selesai,
'ipsrs' => $ipsrs,
'teknisi' => $teknisi,
]);
}
Example this variable $belum_dikerjakan is showing table data and I have fucntion edit on this table ( in modal) .
But this I don't know how to catch data (ipsrs_id) to set where clause in the pluck . I want to change 1 to ipsrs_id form table , but how ?
If I understood the problem then here is the answer
pull only the ids from ipsrs table and pass to Teknisi table whereIn method
$ipsrsIds = DB::table('ipsrs')->pluck('id')->toArray();
$teknisi = Teknisi::whereIn('ipsrs_id' , $ipsrsIds)->pluck('nama_teknisi', 'id');
public function edit($id)
{
$category =Category::findOfFail($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

How to get hasMany relation in laravel?

Pls bear with me . I am working on api with laravel :
The Idea is that I have table called ( cards ) this table contain column called ( service_id ) .
this column has relation with table ( services ).
This is cards database structure in image :
image of database
All thing is good with add one service_id , but now I need to make table cards hasMany services
So How can I do it , and the database structure what will be?
this is my old code to add new card :
public function store(Request $request)
{
$validator = \Validator::make($request->all(), [
'user_id' => 'required|unique:cards|exists:users,id',
'service_id' => 'required',
'numPhone' => 'required',
'location' => 'required',
],[],[
'user_id' => '( User id )',
'service_id' => 'service id',
'numPhone' => 'Phone Number',
]);
if ($validator->fails()){
return $this->apiRespone(null,$validator->errors()->all(),'Some input required');
}
$card = Card::create($request->all());
return $this->apiRespone(new cardResource($card),'Add card Successfully',201);
}
I think you need to create pivot table "cards_services" that has column id, card_id, service_id column and used relationship Sync() method of laravel to store/update.
In cards modal
public function services(){
return $this->belongsToMany('App\Models\Service','cards_services', 'card_id', 'service_id');
}
For save it.
$cards->services()->sync([1,2]); //1 and 2 is service ID and $cards is card modal object
here you have service_id in your cards table
so i think it will be easier to implement service hasMany cards and cards belongsTo service
add this in your service model
public function cards(){return $this->hasMany('App\Cards');}
add this in your cards model
public function service(){return $this->belongsTo('App\Service');}
Note: please rewrite path and Model name according to your requirement

Laravel current id from query results

I create a scope function like this:
scopeSearch($query, $input)
{
$query->orWhere('title' , 'LIKE' , '%' . $input['q'] . '%')
retrun $query;
}
top function return a list of results in articles table.
articles table structure:
id | title | parent_id
1 title1 null
2 title2 1
3 title3 null
I want return all records that they do not have any child and parent_id is null!
for example in top example I only want return third record (id=3).
I know I must try something like this (I define articles() in Article model before)
$query->whereHas('articles' , function ($query) use ($id){$query->where('parent_id' , $id );})
but I do not know how can I get right $id to insert in top code to return right results.
EDIT
public function articles()
{
return $this->hasMany(Article::class , 'parent_id' , 'id');
}
public function childArticles()
{
return $this->belongsTo(Article::class , 'parent_id' , 'id');
}
Create a relationship with child articles too.
$query->doesnthave('articles','childArticles')->get();
Hope this helps.

Laravel using pivot table to generate a raply from database in one request

I am using datatables so I need to make a request to my database and get a return in one json.
I have a table of users and a table that is linking the users to them to specify if they have a manager. I m doing this through a pivot table.
#User#
id
name
#User_user#
user_id
manager_id
I have the following model for the User.php:
public function managers()
{
return $this->belongsToMany('App\User', 'users_users' , 'user_id', 'manager_id')->withPivot('manager_type')->withTimestamps();
}
public function employees()
{
return $this->belongsToMany('App\User', 'users_users' , 'manager_id', 'user_id')->withPivot('manager_type')->withTimestamps();
}
In order to generate my data for Datatables, I am using:
$userList = $this->user->select('id', 'name','email','is_manager', 'region', 'country', 'domain', 'management_code', 'job_role', 'employee_type');
$data = Datatables::of($userList)->make(true);
This gives me the info I need except, I would like to add the manager so that I can use it in datatables. I don't understand how I can configure this in order to get this in 1 reply of the DB using Eloquent.

Laravel sort with eager loading

In Laravel 4.2, we have a User:: model, which has Message::(s). Every Message has a Sender:: which is not a normal user. I want to sort the result dynamically by columns in Sender:: model.
I have tried this but it doesn't work:
$this->sort->dir = 'asc';
$this->sort->by = 'sender_name';
$result = User::find(1)->messages()->with(array('sender' => function($query){
$query->orderBy($this->sort->by , $this->sort->dir );
}))->paginate(10);
User Class:
class User extends Eloquent{
....
public function messages(){
return $this->hasMany('Message' , 'toid' , 'id' );
}
Message Class:
class Message extends Eloquent{
....
public function sender(){
return $this->hasOne('Sender' , 'sender_id' , 'fromid' );
}
Message Table:
id, toid, fromid, text
Sender Tabele:
sender_id, sender_name, ...
User Table:
id,name,....
I can't change the table structure as it is related to another application. Does anybody know what is wrong here?
you are almost near, just you need little modification, pass variable in closure and add get() at the end of orderBY to get records in your desire orders.
$by = 'sender_name';
$dir= 'asc';
$result = User::find(1)
->messages()
->with(array('sender' => function($query) use($by, $dir){
$query->orderBy(by , $dir )->get();
}))->paginate(10);

Resources