How to update a column of a field in Laravel 4? - php

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.'))
}

Related

LARAVEL: How to fetch id dynamically in a query builder?

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);
}

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()]);
}

Showing orders of user in laravel

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.

Laravel 5.2 : Fetch records against logged in user id

I am fetching records in controller :
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
But it returns null.
And Auth::user()->id returns 2 Which is Okay.
Am i missing something ?
You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.
To tell Eloquent to fetch the data, you need to use either get().
Like:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
As a side note, you can simplify your query to be:
$tasks = Task::where('user_id', Auth::user()->id)->get();
Furthermore, on your User model, you could do this:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
And then you can simply do:
$tasks = auth()->user()->tasks;
This is a Relationship in Eloquent as explained in the docs.

Laravel Model get all where $id = Auth::user()->id

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

Categories