I have the following controller where I try to select all the customers of a user (The ones with 'user_id' equal to the 'id' of the authenticated user). I know how to do it in the following way, but as you can see it is not very efficient since it selects more records than necessary.
public function index() // Http/Controllers/CustomerController.php:17
{
$user_id = Auth::id(); // Get user ID
$customers = Customer::all()->where('user_id', $user_id); // Select all users and then filter by ID
return $this->showAll($customers, 200); // Return JSON response with response code
}
Change your $customers = Customer::all()->where('user_id', $user_id); to:
$customers = Customer::where('user_id', $user_id)->get();
https://laravel.com/docs/7.x/eloquent#retrieving-models
Related
I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}
I want to paginate the data according to current logged in user.
this is my controller :
public function index()
{
$dosen = Dosen::paginate(5);
return view('dosen.index', compact('dosen'));
}
I'm assuming you've a user_id column in your Dosen model table. So you can say
$dosen = Dosen::where('user_id', auth()->user()->id)->paginate(5);
return view('dosen.index', compact('dosen'));
You can get current login user by Auth::user()->id
So pass it in your query.
$dosen = Dosen::where('user_id', '=', Auth::user()->id)->paginate(5);
Note:- user_id is your dosen table column name.
You can first filter the result using query and then apply paginate on the result to get the result-set of logged in user only.
Like this,
$doesn_query = Dosen::query();
$doesn_query->where('user','=',$userid); // Replace $userid with logged in user id.
$result = $doesn_query->paginate(5);
How to List all rows from a DB where $id matches the logged user id.
I'm using default Auth from Laravel.
At the moment i can list them all with this method in my controller:
public function index(){
$invoices = Invoice::all();
return view('index', compact('invoices'));
}
But i just want the ones that are from this user which is logged in:
Something like
$invoices = Invoice::where('id', '=', Auth::user()->id);
Your code Seems almost right. I would do:
$invoice = Invoice::where('id', Auth::user()->id)->get();
So basically use the get in order to fetch a collection. And maybe I would separate the user id in a varaible in case that you change the authentication in the future ;)
When using any condition then of course you must need to add the get() method. Otherwise, you can't show your data.
$invoices = Invoice::where('id', '=', Auth::user()->id)->get();
This means that you want to see data on which user is logged in now
I'm trying to do a friendship system in laravel 5 and I'm stuck.
I have a friends_user table which look like this:
id
user_id
friend_id
status
Here is the point, I go to an user page, and Ii wanna see how is my relation with this user, 4 solutions:
We are friends
We're not
He doesn't have accepted the request yet
I have to confirm or not.
I wanna create a method that checks if a user is friend with an other, simple.
I have a 'status' column which is a boolean (0 for pending and 1 for friends)
The perfect solution for me would be to be able in one method to check if:
The users are friend, so either ('user_id', Auth::user()->id)->and ('friend_id', $friend->id) or the inverse ('user_id', $friend->id)->and ('friend_id', Auth::user()->id), it has to check in the 2 senses
I sent request and have to wait for his answer
I received the request and have to accept it.
We're not friend and so, i can add him.
So if you can tell me where i'm wrong here, here's my logic (just for check if users are friend) : User.php
public function isFriend($slug)
{
// Get both user
$user = Auth::user();
$receiver = User::where('slug', $slug)->first();
// get list of friends (so who have status = 1)
$result = Friends::where('status', 1);
// Get users where user id is equal to connected
$result = $result->where('user_id', $user->id)->where('friend_id', $receiver->id);
$result = $result->orWhere('user_id', $receiver->id)->where('friend_id', $user->id);
$result = $result->get();
if(count($result) == 0)
return false;
return true;
}
After I do these checks in my view.
This works pretty much, but only if i (the current user) has sent the request but if it's the inverse it returns me the user even if status is at 0. I think that my $result erase the other ones isn't it? What's the solution so?
I hope it's clear, and if you can tell me how do this in a clean way, it would be great.
That's a common mistake. Beware of your "orWhere" clause.
public function isFriend($slug)
{
// Get both user
$user = Auth::user();
$receiver = User::where('slug', $slug)->first();
// get list of friends (so who have status = 1)
$result = Friends::where('status',1)->where(function($query) use ($receiver,$user)
{
$query->where([
'user_id' => $user->id,
'friend_id' => $receiver_id
])->orWhere([
'user_id' => $receiver->id,
'friend_id' => $user->id
]);
})->get();
return ! $result->isEmpty();
}
I'm trying to call an AJAX request on a route that calls this function updateImpression() in UserController, and this function tries to increment the counter column named "impressions_cpunt" in my 'users' table stored in MySQL. I tried using Eloquent to update the column of one particular user only.
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$impressions_count = $user->impressions_count + 1;
// save() method failed to update my database.
// $user->impressions_count = $impressions_count;
// $user->save();
//update() method does not return anything. Any syntax error here?
//$user->update(array('impressions_count' => $impressions_count));
DB::table('users')
->where('username', $username)
->update(array('impressions_count' => $impressions_count));
$user = User::where('username', '=', $username)->first();
return $user->impressions_count;
}
I think save() function should be work at the first place but my database doesn't get updated and return the original count, and the update() function doesn't even returning any value from the function. This only works when I use DB but I think Eloquent should be better to use since this is Laravel. Is there anything I missed or something wrong with the syntax? I know increments() data type should be used but please allow me to solve this before I change anything.
Update:
This is my database queries shown in Debugbar when I use save() method:
select * from 'users' where 'username'= <test> limit 1
select count(*) as aggregate from 'users' where 'username'= <test>
select count(*) as aggregate from 'users' where 'email'= <test#example.org>
User object (which supposed to be Eloquent child) like any other entity will store its state after changes if your save() call was successful. Therefore, there is no need to update the record explicitly. In your case I would go with something like this:
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$user->impressions_count += 1;
$user->save();
return $user->impressions_count;
}
In Laravel 5.2 you can update specific column by using the following Eloquent builder:
public function update(Request $request, $id) {
$user = User::where('id', $id)->update(['name', $request->name]);
return redirect()->back()->with('status', trans('User has been updated successfully.'))
}