User::all show relationship items - laravel

I Laravel 5.5 I am returning users information like this...
$users = User::all();
return Response::json(array(
'error' => false,
'response' => $users,
));
I have a belongs to many categories relationship setup and would like to also show all of the categories each user belongs to.
Anyone have an example I can see?

Use the with() method to load categories for each user:
$users = User::with('categories')->get();
If you don't need to load all the columns from the categories table, use select() inside the with() closure. Also, since you're using Laravel 5.5 you could use Resource classes for formatting JSON.

Related

Laravel create multiple records in one query with Eloquent and get the created models

I know I can do the following to create multiple records with one query :
$users = [];
$users[] = ['name' => 'Tom'];
$users[] = ['name' => 'Jerry'];
$result = User::insert($users);
The problem of this approach is that ìnsert uses the query builder, and returns a boolean.
What if I wanted to have the created Eloquent models returned ? Would that be possible without having to do another query to retrieve them (how would I do that since I don't know the created ids ?) ?
I'm looking for something like the create method (which returns the created User model), but for multiple inserts (afaik createMany does not work outside of relationships)
Thanks

How to take specifig column from relation ship in laravel

I am getting Consignment model which belongsTo Product type model so when i try to access name of product type i use this query
$consignment->product_types->name
But checked that this queries mean
select* from product_types
In my projectti am using this method many places which is now creating issue. Is there any method i can just take specific columns?
You may specify which relationships should be eager loaded using the [with] method:
$companies = Company::select('id', 'name', 'phone')
->with('customers:id,company_id,name')
->get();
echo '<pre>';
print_r($companies->toArray());
you can restrict it in your query builder:
Consignment::with(['product_types' => function ($query) {
$query->select("id", "consignment_id", "name");
}])->get();

Empty field in view while it has been retrieved with dd Function

I have joined two tables in Clint table controller and Appointment table as below image and dd function showing the data already.
Here is my controller:
and here is result of dd():
but in the view page it's an empty field:
and here is available I am using in the view:
I have seen your controller image and in join statement mistake.
When you join your appointment table to the clients table then you should use foreign keys.
public function show(Client $client) {
abort_if(Gate::denies('client_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$client = DB::table('clients') ->join('appoinments', 'clients.id', '=', 'appoinments.clint_id') ->select('clients.*', 'appoinments.start_time', 'appoinments.finish_time') ->get();
return view('admin.clients.show', compact('client'));
}
I assume in the appointment table you have clint_id.
The variable $client that you are passing to your view is from your Route Model Binding. $clients is the result of your query with the join to appointments which provides the fields start_time and finish_time. You are showing us the output of a dd on $clients which includes those fields, but passing $client to your view which most likely does not have such fields.
You could adjust what you are passing to your view to fix this:
return view('admin.clients.show', [
'client' => $clients,
]);
I am not sure what your purpose is with this method though as the route parameter doesn't end up being used. You probably want to be using that route parameter to filter your query. Though this could be a good place to try using relationships instead of directly joining with query builder.
Also, please do not put up pictures of code. Please edit your question and include the code into the question if you can. Thanks.
Laravel 6.x - Docs - Routing - Route Model Binding

Laravel - categories as url segments, category belongs to many

I'm creating an application where user can have one speciality.
User can in backend create posts assigned to his speciality, and has to associate it to one category.
I'm wondering how to manage categories when a doctor and an lawyer can use the same category, and not display all posts for all specialities where category is the same.
So actually:
user has one speciality
speciality has many categories
category belongs to many specialities
I think i have to create a pivot like category_speciality, as explained in Laravel doc for many to many relationships.
But then i can't figure how to use speciality an category to build dedicated queries and urls.
Any help will be great !
For URL's you could do something like:
web.php
Route::get('/articles/{category}/{specialty}', [
'uses' => 'PostController#index',
'as' => 'posts.index'
]);
where {category} and {specialty} are a unique slug field of their title. This would result in e.g. example.com/articles/deep-sea/fishing.
PostController
public function index($categorySlug, $specialtySlug)
{
$specialty = Specialty::where('slug', '=', '$specialtySlug')->first();
$posts = Posts::where('specialty_id', '=', $specialty->id)->get();
return view('posts.index', compact('posts'));
}
That is assuming you have specialty_id in Posts table and you have correct relationships set up.
This is just an example.

Laravel Eloquent: eager loading of multiple nested relationships

What laravel says:
$books = App\Book::with('author.contacts')->get();
What I need is something like this
$books = App\Book::with('author[contacts,publishers]')->get();
where we eager load multiple relationships within a relationship.
Is this possible?
You can do
$books = App\Book::with('author.contacts','author.publishers')->get();
Laravel documentation on eager loading recommends listing the relationships in an array as follows:
$books = App\Book::with(['author.contacts', 'author.publishers'])->get();
You can have as many relationships as desired. You can also specify which columns should be included for a relationship like this:
//only id, name and email will be returned for author
//id must always be included
$books = App\Book::with(['author: id, name, email', 'author.contacts', 'author.publishers'])->get();
You may also add constrains as follows:
$books = App\Book::with(['author: id, name, email', 'author.contacts' => function ($query) {
$query->where('address', 'like', '%city%');
}, 'author.publishers'])->get();
So, now you can try
$books = App\Book::with(['author' => function($author){
$author->with(['contacts', 'publishers'])->get();
}])->get();
From Laravel 9, the neatest way is the nested array :
$books = App\Book::with(['author' => [
'contacts',
'publishers'
])->get();
Reference
When eager load nested relationships and we want to select just some columns and not all using relationship:id,name, always include the foreign key to the nested models, else they won't load at all.
Fort example, we have orders that have identities that have addresses.
This will not load the address:
User::orders()
->with('identity:id,name', 'identity.address:id,street')
This will load the address because we have supplied the address_id foreign key:
User::orders()
->with('identity:id,address_id,name', 'identity.address:id,street')

Resources