How to get all data combining two models in laravel - laravel

I am using Eloquent and I want to get all data combining two models.
I have two models Courseoffer and Courseoffer_payment.
Inside Courseoffer model I have this function:
public function payment()
{
return $this->hasone('App\Models\Courseoffer_payment');
}
And this is my query :
return Courseoffer::findorfail(10)->payment;
This will give me data of Courseoffer_payment model associated with id 10 but I want all data for Courseoffer as well as Courseoffer_payment associated with id 10.

Try to use with instead like :
return Courseoffer::with('payment')->findorfail(10);
That will return the Courseoffer 10 instance with the payment information.

Related

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

How to query from database when I have different foreign keys?

I am trying to query data from my database and pass the results to a view called events, the problem I have is that one of my queries will always return the same result because in the where condition the $events_id is the same always. Is there a better way to do the querying? A better logic?
This code is from my controller called EventController:
public function index()
{
$firm_id = DB::table('firms')->where('user_id', auth()->id())->value('id');
$events_id = DB::table('events')->where('firm_id', $firm_id)->value('id');
$events = DB::table('events')->where('firm_id', $firm_id)->get()->toArray();
$actual_events = DB::table('actual_events')->where('event_id', $events_id)->get()->toArray();
return view('events',['events' => $events,'actual_events' => $actual_events]);
}
Since the $events_id is the same every time, the $actual_events will only contain the first result.
The image I have uploaded shows the problem, my table's first three columns are fine. Starting from the fourth they contain repeated values:
As I guess, you need something like this:
$event_ids = DB::table('events')->where('firm_id', $firm_id)->pluck('id');
$actual_events = DB::table('actual_events')->whereIn('event_id', $event_ids)->get()->toArray();
or write about your problem in details and I will try to help you.
you just said that your tables have relation together.
in this case it's better you using the eloquent for that,
first you should type the relations in model of each table like this:
class User extends Authenticatable{
public function cities()
{
return $this->hasmany('App\City'); //you should type your relation
}
}
for relations you can use this link: laravel relationships
after that when you compact the $user variable to your view, you can use this syntax for getting the city value relation to this user: $user->cities;.

how to display the current logged on users picture from a relationship laravel

I want to retrieve the user's photo and display it in a thumbnail form which i have stored in public/assets/uploads/thumbnail/. I tried auth()->user()->user_detail->file_name but I can't get it to work. How do you do it ?
you have to first define a relationship if they are stored in different table
like i did in model
public function imagedata() {
return $this->hasMany(Images::class, 'listID', 'id');
}
and after that when you get the user just call this method like this
$listingimg = Listings::findOrfail($id);
and for calling the relationship
foreach (listingimg as $singleIlisting) {
$singleIlisting->imagedata;
}
modify the code according your needs as if needed and by the way relatio is one to many

eloquent return two columns all records

I'm sure this is very simple - I just need two columns from a country database to populate a <select>
Looking at this URL I came up with the code below, but this seems to return an object for each record
http://laravel.com/api/class-Illuminate.Database.Eloquent.Model.html#_all
class countries extends Eloquent
{
}
public static function getCountrySelect()
{
return countries::all(array("name","iso_3166_2"));
}
If you want to populate custom field from database use this:->
countries::lists('name','iso_3166_2');
i.e
countries::lists('coulmnname1','coulmnname2');
and if you want to get suppose first 10 entries for that model use this:
countries::take(10)->get();

Laravel 4: Keeping a table Relationship when reducing structure into several tables

History:
DB: Tables clients and titles
A Client can have many titles but a title can only have one client. So i will use a simple one-to-many relationship as illustrated below:
Client Model
class Client extends Eloquent {
public function titles(){
return $this->hasMany('titles');
}
}
Then i simply use the following to get the requested data for the selected title
$clientTitles = Client::find(1)->titles;
All in all this should list all client associated titles.
My question really comes to this as i am looking to split my data within my titles table into smaller tables as i also use some aspects of the titles data somewhere within the system and do not need to get all of the title details every time.
So i would have another three tables related to the titles data table
Titles, Title_Artwork, Title_Details, Titles_List
Now if i use the same as above i will get all the data within the titles table, but not the other three. So how can i then update my relationship to then scrape the other three title tables so when i need to, i can get all the data, rather.
Or is there another way to do this or NO keep to what i have done an just limit the call to the fields i require?
From what I understood, And lets assume that your Titles model is some what like-
class Titles extends Eloquent{
public function titleartwork(){
return ..
}
public function titledetails(){
return ..
}
public function titlelist(){
return ..
}
}
And your client model is-
class Client extends Eloquent {
public function titles(){
return $this->hasMany('titles');
}
}
So in order to get the data of any of these tables Title_Artwork, Title_Details, Titles_List
you can do this
$clientTitles = Client::with('Titles','Titles.titleartwork','Titles.titlelist')->where('id','=',1)->get();
In terms of Laravel it is known as Eager Loading, to know more you can check the doc
It will also work with multiple nesting, I mean if your Title_Artwork also contains relationship like-
class TitleArtwork extends Eloquent{
public function sometable(){
return ..;
}
}
Then you can get the data of sometable using
$clientTitles = Client::with('Titles','Titles.titleartwork.sometable','Titles.titlelist')->where('id','=',1)->get();

Resources