Get ::all() Model data with Foreign key elements Laravel [duplicate] - laravel

This question already has answers here:
Query relationship Eloquent
(3 answers)
Closed 1 year ago.
In laravel with Model we can get all Table details
Locations::all();
But I want to get with Foreign key data with the all data.
like there is
id , name , location_id
so it has to get
location_id name
So i get it like
id , name, location_id with location_id_Name
Is it possible to get that result by using laravel basic model. Or I have to change some.
There is answer How to retrieve full data of record by its foreign key in laravel? But then I have to create a new function to add more component of each array. Which I don't want as I suspect there should be better way.
Solution which i found
Location::with('locationid')->get();
where loctionid declared in the model Location
public function locationid(){
return $this->belongsTo(Location::class, 'location_id');
}
So now location load with parent. And also it is very much efficient. If anyone know what will better solution please just comment or answer it.
Best answer on stackoverflow look like https://stackoverflow.com/a/66187247/12657567

See the official documentation of Laravel framework. You may need Eager Loading.
https://laravel.com/docs/8.x/eloquent-relationships#eager-loading

Related

Laravel get relation by custom value

Model - User
id [999]
name [foo]
Model - Post (without User Foreign Key)
id [1]
unique_key [USR_00000999]
data [bar]
I would like to get all user with related posts (one to many) by using "custom key" value, is this possible with build in eloquent?
I only manage to looping using foreach one by one with
Post::query()
->where('unique_key', sprintf('USR_%08d', $user_id))
->count();
That is not built-into Laravel by default... if you want to know why it's because it's not a common thing that everyone does...
BUT, you can use scope query so you don't need to do the sprintf everytime...
Laravel Query Scopes Documentation
But I want to ask, why wouldn't you just add user_id on your post table and just have an Accessors on your post model for generating the unique_key? That would be much easier on my perspective...
Laravel Accessor Documentation
UPDATE: (See Comment)
Is it possible to have an empty user_id on Posts table?
then populate it when the user is created?
say you have a posts with key of USR_00000999... and you have a user with an id of 999... when you create that user you'll just have to update all posts with key of USR_00000999 to have a user_id of 999...

Insert id from table to another table in laravel +vue.js

first image
second image
I want to get Id from students table where i want insert this id in differs table . I don't really know how to explain it but maybe if you see my codes, you would understand. I have already finish making the relationship between this 2 tables already
my student controller
this my differ controller but I do not know any idea about if this code true or no
first: 'app\Differ'? but Differ is in App\Models
you can use hasOne(Differ::class); when Student model and differ in the same folder
the second thing you should know, when using functions of relationship in laravel such as hasOne, a foreign key should be named by student_id in Differ or
you show it in function like hasOne(Differ::class,'id_student','id')

Can this block of code of mine can be improved

[This is to populate data from two tables that one has two foreign keys from the same column as reference on the other table]
https://i.stack.imgur.com/D8fiv.png
[This is my schema for the table with the foreign key]
https://i.stack.imgur.com/eYDL0.png
This is written in laravel and it is working however i have an itchy feeling that this is wrong
As someone else has commented, you should put the code in your question. More context might also be necessary as it's not clear what you are trying to return from your view(). Are you returning $citizen, $family, or both? It would also be helpful to include what version of Laravel you are using. I'll assume you are using the latest Laravel 8.
Your code should work but you are making more work for yourself if you don't utilize Laravel's relationships. If you do, all the query stuff you have in your code can be reduced to just a few short lines of code such as this:
public function view(Citizen $citizen)
{
$citizen->load('family');
return $citizen;
}
Database Migration
You can shorten your migration by using foreignId(). See docs for details
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
Before:
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('citizens');
After:
$table->foreignId('client_id')->constrained();
Route Model Binding
I'm assuming your view() method is in your controller and is called from a route. Since the one parameter required is the client's id, you can use Route Model Binding and skip fetching the client from the database.
https://laravel.com/docs/8.x/routing#route-model-binding
public function view(Citizen $citizen)
{
// your code
}
Relationships
You seem to have relationships set up but you aren't using them to load data. You should be able to load the related objects without any manual queries.
If you have a belongsTo(One to Many) relationship on the Citizen model to the Family model, you can load it like this:
$citizen->load('family');
or just use it like this
$relationship = $citizen->family->relationship;
I don't know what the relationships between your models are but you should read up on the different relationship types in the docs.
https://laravel.com/docs/8.x/eloquent-relationships

How to Get Order Details per a single User in Laravel 7

I am making a multi-vendor ecommerce website using Laravel 7. I am trying to make an Order History page where in a single can user can view only his/her own orders. I am having a problem building the query on my OrderHistoryController. These are the codes on my controller:
$users = User::get();
$orders = Order::find($users);
return view('order-history', compact('orders'));
And I'm trying to loop $orders on my blade file. I have:
#foreach ($orders as $order)
<div>{{ $order->id}}</div>
<div>{{ $order->grand_total}}</div>
#endforeach
I am trying to pass the order id and order grand total to my view. I don't get any error however it shows a different order details from a different customer. How do I do this?
You should use MySQL (or any other database you are using) table relationships and foreign keys.
So, your orders table, should have columns id, user_id, date, and so on. The important thing is user_id column. You want to make that column a foreign key. That basically means that user_id will hold an id value from another table, in this case user. See how to make foreign key columns in laravel migrations here.
Next up is to use Laravel's built in model relationships. You can read more about them here. Basically, in your orders model you want to have a function user which returns $this->belongsTo(App\Models\User::class) and in your user model you want to have a function orders which returns $this->hasMany(App\Models\Order::class) (or whatever the namespace is for both of them).
That way, you can call $user->orders and get a collection of Order models which will contain only the orders of that particular user.
Definitely read the documentation carefully and learn basic concepts of the framework first and how relational databases function!
You can get a lot of this information just by googling it or reading the documentation of Laravel or any other framework you plan on using! Good luck learning :)

How to list related blog posts in OctoberCMS

I am building an App with OctoberCMS and wanted to list related blog posts at the bottom of each post page basing on categories. I figured out rainlab_blog_posts table does not have a foreign key pointing to blog categories table. To achieve what wanted I thought of extending the blog_posts table and added category_id as foreign key using a plugin. I defined foreign key constraints in table migration. Everthing seem to be fine. My challenge is, How can I insert category id in posts table each time a new post is created. OctoberCMS create post backend has an option where the author assigns a category to a new blog post by selecting from list. Just don't understand how to pass this category id and insert into rainlab_blog_posts table in category_id field.
This is what I want to achieve in my API:
routes.php
use Rainlab\Blog\Models\Post;
Route::get('apiv1/related-posts/{postid}',function($id)
{
$post = Post::where('id',$id)->first();
$posts = Post::where('category_id',$post->category_id)
->where('id','!=',$id)
->orderBy('views','desc')
->get()->take(5);
return $posts;
});
Or if there is a better way of achieving this will appreciate. Cheers!
Hmm seems something wrong here,
As first I can see from Blog Plugin that Blog <=> Category it is MM relation so you will not find category_id in rainlab_blog_posts table as all relation is maintained by this mm-relation table rainlab_blog_posts_categories.
So I think you will select only one category for blog so you can get related blogs for only that category. [ assuming from your code and description ]
we can utilize relationships for that.
So your code can look like this
use Rainlab\Blog\Models\Post;
Route::get('apiv1/related-posts/{postid}', function($id)
{
$post = Post::where('id',$id)->first();
// we need this because there will be mm relation so
// we fetch first category and this will be based on
// [ name sorting - does not matter as there will be only one cat. ]
$firstCategory = $post->categories()->first();
// now we fetch only that post which are related to that category
// but we skip current post and sort them and pick 5 posts
$posts = $firstCategory->posts()
->where('id', '!=', $id)
->orderBy('views','desc')
->limit(5) // use limit instead of take()
->get();
// use limit instead of take() as we don't need extra data so
// just put limit in sql rather fetching it from db then
// putting limit by code - limit() is more optimised way
return $posts;
});
Good thing now you don't need to add that category_id field on rainlab_blog_posts. So, I guess now you Also don't need to worry about adding it during post insertion.
if any doubts please comment.
Incase you simply want to display related blog posts without having to customize the blog database, there is an OctoberCMS plugin called Related Articles
that requires rainlab blog plugin. It will display all the other articles belonging to the post's category.
On your Backend menu, go to settings,on System, go to Updates and Plugins.
Go to Install plugins. Search for plugin Related articles. The creator is Tallpro. Install it.
Go to CMS. On the page you want related articles, go to components and drag Related articles. Save and preview it. You can also fork the component to edit how you want your related articles to be displayed. You will find more information on the documentation.
If you encounter any problems feel free to inquire or you can check out the plugin reviews for problems faced and their solution.

Resources