Laravel many to many retrieve data across multi table - php

Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.

Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;

Related

show data if you have user id - laravel

I am creating a data list and I print it with foreach, i would like it to display the data only if user_id matches the user_id reading the data. (previously I already have the user authentication created)
I want the users who enter to only see the data that contains their user_id.
I already made the relationship between the users table 'id' field with user_id
pass the data with:
public function index()
{
$servicios = App\Servicio::all();
return view('home', compact('servicios'));
}
How do I show the data that corresponds to the user_id of each one without others seeing their data??
You could set up a relationship inside the User.php model.
public function servicios() {
return $this->hasMany(Servicio::class);
}
Then in your controller:
public function index()
{
$servicios = auth()->user()->servicios;
return view('home', compact('servicios'));
}
You can get the user's list of services easily using Auth::user(), example:
User::with(['servicios'])->find(Auth::id());
you should get the user from your request, then filter by its id ...
public function index()
{
$user_id=app('request')->user()->id;
$servicios = App\Servicio::where('user_id',$user_id)->all();
return view('home', compact('servicios'));
}
the user will be present in your request, to make sure of that you should but
the route that use this method in (auth) middleware

Foreign key query laravel - the eloquent way

I am trying to find a way to write eloquent way to query my model.
I have a Form model every form belongs to a User (Form:User = 1:1). Each User has a State and a City associated with them. Admin reviews a Form and each admin can be assigned to multiple State and City.
I want to find the Form that belongs to an Admin.
This is the forms function in Admin.php (Model)
public function forms()
{
//cities
$cities = $this->cities->pluck('name');
//states
$states = $this->states->pluck('name');
//get all form from the user and states
$forms = Form::whereHas('user',function ($query) use($cities,$states)
{
// find form from his states or cities
$query->whereIn('state',$states)->orWhereIn('city',$cities);
});
return $forms;
}
Currently it returns all the forms.
Any help will be appreciated!!!
You can try this:
$citiesForms =$this->cities->forms->toArray();
$statesForms = $this->states->forms->toArray();
return array_merge($citiesForms, $statesForms);
and you can look for hasManyThrough to make this done in one line

How to joins table in Laravel 5.2?

I am beginner in Laravel Framework.I have searched for my problem and get some solution but those are not solve my problem.So,
profiles table:
I want to need to fill up userID column when any user create a profiles.For this i am trying to code something like this:
Profile model:
public function users(){
return $this->belongsTo('App\User','userID');
}
And User Model:
public function profiles()
{
return $this->hasMany('App\Profile');
}
In this way its keep null value every time.How can i solve this?
Thanks in advanced.
So assuming you have the following (which you kind of do)
public function profiles()
{
return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}
<?php
// Profile.php (Model)
public function user()
{
$this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}
You have a few options, you can either when creating the profile, assign the user_id (as long as it is in the fillable fields.
$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();
Or since we have a relationship you should be able to do something like this
$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.
Hopefully that sheds some light
While inserting Data into Profile Table, you just need to do as follows:
$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();
There is no need to join the tables for inserting the value in Profile Table for here. Hope this helps you

Update a column that exist in the many to many relationship table in laravel 5.2

I have three tables which are User table, Events table, and Events_user table. I have four columns in the Events_user table which are :
Schema::create('events_user', function(Blueprint $table){
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('events_id')->unsigned()->index();
$table->foreign('events_id')->references('id')->on('events')->onDelete('cascade');
$table->integer('eventstatus')->unsigned()->index();
$table->timestamps();
});
I have a function which add an event base on the user id, show one user can have many of the events. But the event can share to other user. The function is like this :
public function store(EventsRequests $request){
$id = Auth::user()->id;
$events= Events::create($request->all());
$events->user()->attach($id); //Store the User_ID and the Event_ID at the events_user table.
Flash::success('Your event has been created!');
return redirect('/');//Return into home page
// return $events;
}
Then it will help me update my events_user table, but how do I update the column which is eventstatus?
Can anyone show me how could I update it? Cause I want to use the eventstatus help me determine if there is '1' then cant be edit, then the edit button will disappear.
How many way can accomplish to the function?
For the show page:
I have use the function when the user click the event that exist on the calendar view, then the javascript will pass the id back and redirect to the view with the id.
public function show($id){
// $user_id=Auth::user()->name;
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents','user'));
}
How about when i want to pass the eventstatus into the view? So i can check on my view, if the eventstatus equal to one, the edit button wont show up.
Updated relationship model
User.php
public function events(){
return $this->belongsToMany('App\Events');
}
Events.php
public function user(){
return $this->belongsToMany('App\User')->withPivot('eventstatus');
}
If you want to update the field while making the association, you can pass an array of field=>value pairs as the second parameter to the attach() method. You can read in the documentation here.
$events->users()->attach($id, ['eventstatus' => 1]);
If you want to update the field for an existing association, you can pass an array of field=>value pairs to the save() method:
$user = Auth::user();
$event = $user->events()->first();
$user->events()->save($event, ['eventstatus' => 1]);
If you want to access the field to read the data, you can access it through the pivot property:
$user = Auth::user();
foreach ($user->events as $event) {
echo $event->pivot->eventstatus;
}
In addition to all of this, you need to make sure your relationship definitions include access to the extra property:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}
Edit
updated answer for additional question
To get the information you're looking for, you need to be able to get to the pivot record. The pivot record is available on the models in the loaded relationship.
Since you have the Event, you need to go through the related User models, find the user you want (assuming the logged in user), and then get the status off of the pivot attribute on that user.
public function show($id)
{
// get your event
$showevents = Events::findOrFail($id);
// get your user
$user = Auth::user();
// default status to send to view
$status = 0;
// if there is a user...
if ($user) {
// find the user in the "user" relationship
// NB: calling "find" on a Collection, not a query
$eventUser = $showevents->user->find($user->id);
// if the user is associated to this event,
// get the status off the pivot table,
// otherwise just set the default status
$status = $eventUser ? $eventUser->pivot->eventstatus : $status;
}
// add your status to the data sent to the view
return view('events.show', compact('showevents', 'user', 'status'));
}
In addition to all this, make sure both relationship definitions include the ->withPivot('eventstatus'). You want to make sure you can get at it from both sides, if need be.
Can you share your event and user model relationship code?
so , it will help me to get into deep.
OR
you can try this in event model like:
public function user()
{
return $this->belongsToMany('App\Event')
->withPivot('eventstatus')
->withTimestamps();
}
then while updating you can do something like this iam not sure but hope this help.
$events->user()->attach($id,['eventstatus' => 1]);
Thanks
For fetching extra column:
public function show($id){
$showevents = Events::findOrFail($id);
$event_status = $showevents->pivot->eventstatus;
return view('events.show',compact('showevents','event_status'));
}
but for that you have to define this column in models:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}

Dynamically populating the dropdown menus in PHP Cake. Access Model from another Model?

I am building a Cake PHP application. Different users have different properties so I use two objects to store a user for example
User hasOne Student / Student belongs to User
User hasOne Lecturer / Lecturer belongs to User
The profile edit page will allow the User to edit all their details for both objects. I've set up the form and used saveAll so save both objects. My problem is dynamically populating the dropdown menus depending on which role the user has.
For example the counties field. Admin does not have an address whereas Student and Lecturer do. I have setup my Country model to find all my counties and put them into opt-groups in the select box (sorting them by country as shown here Dropdown list with dyanmic optgroup)
I can do this fine inside the Students/LecturersController as they allow me to access the Country model as I set $uses variable. I do not want to do this inside the UsersController as not all user roles have an address and an address is never stored inside the User object. I tried putting the code in the model but then I don't know how to access other Models inside a Model. Up to now I've had no problem building the app and I feel that I may have made a bad design decision somewhere or there's something I'm not understanding properly.
Essentially I'm asking how do I implement the setForForm() function below.
public function edit() {
//get user
$user = $this->Auth->user();
//get role
$role = $user['User']['role'];
if ($this->request->is('post') || $this->request->is('put')) {
//get IDs
$userID = $user['User']['id'];
$roleID = $user[$role]['id'];
//set IDs
$this->request->data[$role]['user_id'] = $userID;
$this->request->data[$role]['id'] = $roleID;
$this->request->data['User']['id'] = $userID;
//delete data for role that is not theirs
foreach ($this->request->data as $key => $value) {
if($key !== 'User' && $key !== $role) {
unset($this->request->data[$key]);
}
}
if ($this->User->saveAll($this->request->data)) {
//update logged in user
$this->Auth->login($this->User->$role->findByUserId($userID));
$this->Session->setFlash('Changes saved successfully.');
} else {
$this->Session->setFlash(__('Please try again.'));
}
}
//set role for easy access
$this->set(compact('role'));
//sets required variables for role form
$this->User->$role->setForForm();
//fills in form on first request
if (!$this->request->data) {
$this->request->data = $user;
}
//render form depending on role
$this->render(strtolower('edit_' . $role));
}
//this is the method I would like to implement in the Student/Lecturer model somehow
public function setForForm() {
$counties = $this->Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
Not sure if I get your question correct, but I think what you want is the following:
User hasOne Student / Student belongs to User
and
Student hasOne Country / Country belongsTo Student
(and the same for Lectureres)
then from your UsersController you can do:
$this->User->Student->Country->findCountiesByCountry();
hope that helps
--
EDIT:
if you want to want to use $role instead of Student/Lecturer you would have to do it like this:
$this->User->{$role}->Country->findCountiesByCountry();
In the end I decided to just load counties in the user controller regardless of whether the form will need them or not since Admin is the only user that doesn't need them.
Try something like this:
public function setForForm() {
App::import('model', 'Country');
$Country = New Country();
$counties = $Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
I don't know is this the best solution or not but it is working at least :)
Edited
Here is another mistake. Its not recommended to set variable from model to view , you can return data that will be set then in edit function normally set it to the view , but anyways if you need to set from model to the view you can load controller class to your model using App::import(); and use set function.

Categories