I'm quite new to Laravel and I'm confused with how I have to retrieve data inputted by certain users.
In my project, there is a user profile that should display all form submissions by the user.
Here is my controller function:
public function clientAccount(BookingRequest $bookings)
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = BookingRequest::with(Auth::id())->with('client')->first(); //unsure about here//
return view('client.account', compact('client','bookings'));
}
Here is my model:
public function client()
{
return $this->belongsTo('App\Client', 'client_id', 'user_id');
}
How do I fix this?
EDIT:
I tried using this but somehow I don't get any display
$bookings = BookingRequest::where('client_id',Auth::id());
If the relationship needs to be one to many meaning one Client has many Bookings, than in your Client model you should have the following function:
public function bookings()
{
return $this->hasMany(BookingRequest::class);
}
then you just need to find the client, and for him you just use
$client->bookings()
it will list all the bookings for that client.
Following on from nakov:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->bookings();
return view ('client.account')->with('bookings', $bookings)
}
And in your user profile view:
foreach($bookings as $booking){
// do something with each booking
// e.g. var_dump($booking) to see the data you're working with
}
Thanks for all your responses!
I'm now able to retrieve data by using this:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->booking()->with('client')->get();
return view('client.account', compact('client','bookings'));
}
and in my model, I used this instead
public function booking()
{
return $this->hasMany('App\BookingRequest', 'client_id', 'user_id');
}
Related
I have a laravel project where a User can have many Client class. The Client can have many Session and and a Session can have many Assessment and many Plan. I am using hasManyThrough on the Client to get Assessment and Plan. Each Assessment and Plan has a review_date timestamp saved into the database.
What I'd like to do is get all the Assessment and Plan for any Client with their review_date as today. Ideally something like:
$events = Auth::user()->reviews()->today();
What I don't know how to do it make the reviews function, because it's essentially combining 2 relationships.
Can anyone help me out?
User.php
public function clients()
{
return $this->hasMany(Client::class);
}
public function assessments()
{
return $this->hasManyThrough(Assessment::class, Client::class);
}
public function plans()
{
return $this->hasManyThrough(Plan::class, Client::class);
}
public function reviews()
{
// return all assessments and plans
}
public function scopeToday(Builder $query)
{
$query->whereDate('review_date', Carbon::today());
}
Client.php
public function assessments()
{
return $this->hasManyThrough(Assessment::class, Session::class);
}
public function plans()
{
return $this->hasManyThrough(Plan::class, Session::class);
}
Session.php
public function assessments()
{
return $this->hasMany(Assessment::class);
}
public function plans()
{
return $this->hasMany(Plan::class);
}
You can get a collection from both methods, so you could simply merge the 2 together. (Be warned, this will lead to ugly code later when you have to check object types during the loop.) You can't chain the scope method, since you aren't getting back a relationship object, but you could pass the date as a parameter instead, or just fix it at today's date if you'll never need other dates.
public function reviews(Carbon $date)
{
return $this
->assessments()
->whereDate('review_date', $date)
->get()
->toBase()
->merge(
$this->plans()->whereDate('review_date', $date)->get()->toBase()
)
->sortBy('review_date');
}
And then call it like this:
$date = now();
$events = Auth::user()->reviews($date);
I have two data tables related to each other by the belongstomany relationship. And when I am fetching data from its api controllers with selecting only two column keys ['id','title'] yet it returns some extra data in the response object.
modelcode:
public function place(){
return $this->belongsToMany(Place::class,'city_place')->select(array('id', 'title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get());
}
enter image description here
You must indicate the name of the table in front of the fields.
model Place code:
protected $columns = ['places.id', 'places.title']; //all column for select
public function scopeExclude($query, $value = [])
{
return $query->select(\array_diff($this->columns, (array) $value));
}
model City code:
public function place()
{
return $this->belongsToMany(Place::class,'city_place', 'city_id', 'place_id');
}
controller code:
public function ofcity($id)
{
$cities = City::findOrFail($id)->place()->exclude(['featured_image'])->get()->toArray();
return response()->json(['cities' => $cities], 200);
}
In exclude skip all the fields that need not to be shown.
Thanks everyone here helping me out but none of the above solution worked..I figured it out after trying different functions and spending hours on this.
model Place code:
public function place(){
return $this->belongsToMany(Place::class,'city_place','city_id','place_id')->select(array('places.id', 'places.title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get()->map(function ($item,$key) {
return ['id' => $item['id'],'title'=>$item['title']];
})
);
I'am new to laravel and had a hard time for eloquent ORM, I like to retrieve Favourite items from the table with specific user id, but seem I don't find a way to display the data correctly.
I refer and copied the favourite model code from here
Model: Favourite
class Favourite extends BaseModel
{
public function favouritable()
{
return $this->morphTo();
}
}
Model: Course
public function favourites()
{
return $this->morphMany(Favourite::class, 'favouritable');
}
public function myFavourite()
{
return $this->favourites()->where('favor_user', '=', auth()->user()->id);
}
Controller: FavouriteController#index
public function index()
{
$course = new Course();
$myfavs = $course->myFavourite();
//dd($myfavs);
$this->vdata(compact('myfavs'));
return view('front.favorites', $this->vdata);
}
In blade view, but return empty/blank data:
#foreach($myfavs as $myfav)
{{ $myfav->$course_name }}
#endforeach
When i dd($myfavs) it display pretty bunches of data that i couldn't find the data that is stored in the favourites table.
I think you have added the conditions but forgot get the results with one of the methods to do so.
Try :
$myfavs = $course->myFavourite()->get();
Or :
$myfavs = $course->myFavourite()->take(<N>)->get;
Or
::all()
etc. take a look at : https://laravel.com/docs/5.8/eloquent#retrieving-models
I'm building a small application on laravel 5.4 where I'm having following models and relationship:
Interaction Model:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps();
}
Contact Model:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
and Company Model:
public function contacts()
{
return $this->belongsToMany('App\Contact', 'company_contact', 'company_id','contact_id');
}
Now I'm fetching some data something like this:
$tempData['contacts'] = $interaction->contactsAssociation()->with('company')->get();
I want to extract company data from the pivot table which is mentioned in the relationship. Currently I can't find solution so I have to do:
$tempData['contacts'] = $interaction->contactsAssociation()->get();
$companies = [];
foreach($tempData['contacts'] as $contact)
{
$companies[] = Company::find($contact->pivot->company_id);
}
$tempData['company'] = $companies;
Guide me on this, thanks,
You can pass an array to the withPivot() function with every field you want to retrieve:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')
->withPivot(['company_id', 'other_field'])
->withTimestamps();
}
Hope this helps you.
I have users, and users belong to a dealership.
Upon user registration, I'm trying to save a new user, and a new dealership.
User database has a dealership_id column, which I want to be populated with the ID of the newly created dealership.
This is my current code in the UserController store method.
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Trying to use $user->push(); User data gets updated, but dealership is not created or updated.
Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.
Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}
To save a User from the Dealership perspective, you do this:
$dealership->users()->save($user);
To associate a dealership with a user, you do this:
$user->dealership()->associate($dealership);
$user->save();
Please check this answer to see the difference of push() and save()
You will need to define correctly your models relationships as per documentation
If this is done correctly, it should work .
This is what push() does :
/**
* Save the model and all of its relationships.
*
* #return bool
*/
public function push()
{
if ( ! $this->save()) return false;
// To sync all of the relationships to the database, we will simply spin through
// the relationships and save each model via this "push" method, which allows
// us to recurse into all of these nested relations for the model instance.
foreach ($this->relations as $models)
{
foreach (Collection::make($models) as $model)
{
if ( ! $model->push()) return false;
}
}
return true;
}
In your case, you have a one (dealership) belongs to many (users)
In your Users model :
class Users extends Eloquent {
public function dealership()
{
return $this->belongsTo('Dealership');
}
}
In the example above, Eloquent will look for a dealership_id column on the users table.
In your Dealership Model :
class Dealership extends Eloquent {
public function users()
{
return $this->hasMany('User');
}
}
In your store function :
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->dealership = new Dealership();
$user->dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Learn here more about eloquent relationships
Also please take a look at my answer here
By using push on the User model, Laravel is basically recursively calling save on all the related models (which, in this case, is none, since you haven't associated any other models to it yet).
Therefore, in order to accomplish what you're trying to do, you can do first create the user then associate the dealership with it by doing the following:
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->dealerships()->save($dealership);
return "User Saved";
However, prior to doing this, you must ensure your User and Dealership models have their relationships set up correctly:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}
This is how I manage to do it.
In your controller: (Laravel 5)
use Auth;
$dealership->user = Auth::user()->ref_user->staff_id;