Showing orders of user in laravel - php

I'm trying to give ability on user to see his orders. How can I query the database.. I'm trying something like this but I got empty page.. I mean nothing from database. May be my query ins't correct.
This is my controller
public function viewOrders() {
$user_order = self::$user->user_id;
$orders = Order::where('user_id', '=', $user_order);
return View::make('site.users.orders', [
'orders' => $orders
]);
}
Am I getting correctly user_id here? I'm not sure...
Update: I have this in my User model
public function orders() {
return $this->hasMany('Order', 'user_id', 'user_id');
}

Ok, so based on your route+button+model do it like this
$orders = self::$user->orders()->orderBy('order_id', 'asc')->get();
return View::make('site.users.orders', [
'orders' => $orders
]);
this should work.. You can remove orderBy clause if you don't need it.

If you have Authentication set properly you can do the following.
public function viewOrders(){
$user = Auth::user();
return view('site.users.orders',[
'orders' => $user->orders
]);
}
When you use the relationship without using the calling parentheses you get a collection of models which are queried if they're not already loaded. This is called lazy loading, if you want to load a relationship before accessing it you can use eager loading. In this case, it is not necessary though.

Related

Laravel using groupBy in with relationship doesn't work properly

Probably my mistake but i couldn't realize where my mistake is.
I have customer model which has schedule_registers() relation
public function schedule_registers()
{
return $this->hasMany('App\Models\ScheduleRegister', 'customer_id', 'id');
}
I also have ScheduleRegister model which has teacher() relation
public function teacher()
{
return $this->belongsTo('App\Models\User', 'teacher_id', 'id');
}
I get data in CustomerController like this (i don't use ->get() because i'm sending this data to datatable);
$customer_index = Customer::with([
'company',
'schedule_registers',
'schedule_registers.teacher',
]);
This query gives me that output;
https://jsonblob.com/915606370225766400
and when i try to use group by teacher_id and change query to this;
$customer_index = Customer::with([
'company',
'schedule_registers.teacher',
'schedule_registers' => function ($q) {
$q->groupBy('schedule_registers.teacher_id');
},
]);
output turns to this;
https://jsonblob.com/915605962518446080
In brief, when i try to use groupBy, i doesn't get any error, but get wrong output. If you could check outputs, when i use groupBy, some schedule_registers data becomes empty but some doesn't.
What is the right way to use groupBy in that situation?

Laravel : How to get all the rows from a table except the first one?

I want to select all the users in my table "User" except the first One cause its the admin,
im using this function index in my controller but it doesn't work .
public function index()
{
// this '!=' for handling the 1 row
$user = User::where('id', '!=', auth()->id())->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}
Better to used here whereNotIn Method
Note: first you find the admin role users and create a static array
$exceptThisUserIds = [1];
$user = User::whereNotIn('id', $exceptThisUserIds)->get();
It's not a good idea to specify the admin user with just id. A better design would be using some sort of a flag like is_admin as a property of your User model.
Still you can use the following code to get the users who have an id greater than 1:
User::where('id', '>', 1)->get()
For getting data skipping the first one you should use skip() method and follow the code like below
public function index()
{
$user = User::orderBy('id','asc')->skip(1)->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}

Too few arguments for view error with laravel

I'm having a problem with laravel., I'm trying to send the variable $codes on my view :
$codes = Code::where('user', $id)->get();
return view('user.edit', ['user' => $user,'codes' => $codes]);
But I get that error Too few arguments to function e(), 0 passed in
The variable $user goes well but not the variable code, anyone have an idea for a solution?
Thank you all
use this:-
return view('user.edit')->with('codes',$codes);
you can get the user with :-
Auth::user()->name;
I'm pretty sure, if you are following Laravel naming conventions, in your eloquent query the column name is user_id and not user. Also if you are using such querys, and you have foreign, you can define relations in your models, like the following:
Code Model
public function user
{
$this->belongsTo(User::class);
}
User Model
public function codes
{
$this->hasMany(Code::class);
}
Instead of line
$codes = Code::where('user', $id)->get();
You can go with:
$codes = $user->codes();
If you don't have the foreigns in your database
$codes = Code::where('user_id', $id)->get();
If non of these helps, please dd() your variables before returning the view, and share result with me in comment. In laravel 7 how you return view is good.

What is the best way to select comments with user data and additional with Laravel?

Im trying to make list with comments, including data about user and his car, that are stored in another tables.
Controller contained such query:
Charging::available()
->with('some.ports', 'shares')
->find($id);
And I rewrote it to such:
Charging::available()
->with('some.ports', 'shares')
->with('chargingComments.user')
->with('chargingComments.car')
->find($id);
Thats how ChargingComments model looks like:
public function comments() {
return $this->belongsTo(\App\Models\Charging::class);
}
public function user() {
return $this->belongsTo(\App\Models\User::class);
}
public function car() {
// here 'id' is the row in the table with users cars
// 'car_id' is in the table with comments
return $this->hasOne(\App\Models\UserCar::class, 'id', 'car_id');
}
It returns me data about each comments` user and his car, but btw I have to somehow limit result to 10 rows. I tried to add
'user' => function($query) {
return $query->take(10);
}])
But it didnt work.
Im sure that should be the better way to write this code, but dont know how
try this
Charging::with('some.ports', 'shares')->with('chargingComments.user')->with('chargingComments.car')->find($id)->latest()->take(10)->get();

Laravel get one value from eager load

I've got this query in Laravel that's returning all forums with some extra information:
return Forum::with(['messages.user' => function($query){
$query->select('id', 'name');
}])->withCount('messages')->paginate(10);
but now it eager loads all related messages as well but I only need the author from a message. How could I get this result?
Assuming the table you have for your Message model is messages and that it has the columns forum_id and user_id, and the table for your User model is users you could just define a belongsToMany and get the information that way:
public function users()
{
return $this->belongsToMany(User::class, 'messages')->distinct();
}
then:
return Forum::with(['users' => function($query){
$query->select('users.id', 'users.name');
}])->withCount('messages')->paginate(10);
Hope this helps!
Without eager loading,
//for a particular forum
//Get a forum entity
$forum = Forum::find($id);
// Get its messages as a Collection
$forumMessages = $forum->messages;
// Iterate over each message on the Collection to find its author. This will look for id in the User model based on the 'author_id' stored by you in the message table.The collection $forumMessages will now have the author's name. This is just to give you an idea. Structure accordingly to your needs.
$forumMessages->each(function ($message){
$message->author = User::find($message->author_id)->name;
});
Try using
return Forum::with([
'messages' => function ($messages) {
return $messages->with([
'user' => function ($user) {
return $user->select('id', 'name');
}
])->select('id', 'author'); // you get author from messages
}
])->withCount('messages')->paginate(10);
This also eager loads but you only get id and author. id is needed to make the relationship with user.

Categories