I would like to create an orderBy ('created_at', 'desc') and paginate, for my articles posted in my account, here is my code.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'events' => $user->events,
'articles' => $user->articles,
]);
}
Assuming the relationship is correct on the User model:
'articles' => $user->articles()->orderByDesc('created_at')->paginate()
Related
I want to show from UserController how many products the User used and user information. I have created two Resources for it. SO I search him using $id Here is My UserController code
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
And here is my UserProductResource
<?php
namespace App\Http\Resources;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
class UserProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'profile_img' => $this->profile_img,
'products' => ProductResource::make($this->products),
];
}
}
And The error is
My Route is:
Route::get('/show-product/{id}', [UserController::class, 'showProduct']);
Try this solution:
You have a error in this query
$products = Product::where('user_id', $user_id)->get();
because $user_id is an object of the User, not a single value.
Your Code:
public function show($id)
{
//
$user_id = User::find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user_id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
New Code:
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
find($id) returns an object so you cant pass object in where(). Replace your below line
$products = Product::where('user_id', $user_id)->get();
with this line
$products = Product::where('user_id', $user_id->id)->get();
it will work.
new UserProductResource($products)
Here Object of Products is passed in resource file and if we check fields in UserProductResource they look like fields existing in User model.
Will $products have any field or relation like products ?
$products is a collection so UserProductResource::collection() should be used.
Ideally you should make relationship between User and Product and do this
$user = User::with('products')->find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
return response()->json([
'data' => new UserProductResource($user),
'status' => 200
], 200);
and as there can be multiple products in UserProductResource you can do this
'products' => ProductResource::collection($this->products),
I have the following login controller :
public function userLogin(Request $request) {
$rules = [
'email' => 'required|exists:users',
'password' => 'required'
];
$request->validate($rules);
$data = [
'email' => $request->get('email'),
'password' => $request->get('password'),
];
if(Auth::attempt($data))
{
$user = Auth::User();
$userid = Auth::User()->id;
return response()->json([
'user' => $user,
'token' => $user->createToken('yourAppName')->accessToken ,
$userid
]);
}
else
{
return response()->json('Unauthorized', 401);
}
}
My web.php ( Token is generated with Laravel Passport )
Route::get('/customize/{id}', function ($id) {
if (
User::where('id', Auth::User()->id)->whereHas('profile', function ($query) use ($id) {
return $query->where('id', $id);
})
->exists()
) {
return view( 'welcome' );
}
return "no";
});
For some reason, when testing my logincontroller with POSTMAN, I actually receive a value for Auth::User()->id . But in web.php I receive Trying to get property 'id' of non-object. Any idea ?
here is a solution
you can find that user in db with email and password you have and get its id
and then use LoginUsingId($id) to login your user
Find out why you are not considered as an authenticated user. I can guess you send Authentication token in your request headers when you use Postman. that this is not possible when you hit the address in the browser directly.
I'm using laravel. I'm trying to create a badge in the navbar and getting the number of rows from a specific table in the database. I have the following codes for the navbar:
<span class='badge badge-pill badge-info'>
#php !empty(session('notifications.all2')) ? print(array_sum(session('notifications.all2'))) : ""
#endphp
</span>
and this for the controller:
class NotificationsController extends Controller
{
public function index ()
{
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
$user = User::where('id', auth::id())
->select('id')
->first();
if(count($settings) == 0)
{
$tasks = Tasks::all();
foreach ($tasks as $task)
{
NotificationSettings::create([
'user_id' => $user->id,
'name' => $task->name,
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$checkRestockTask = Tasks::where('name', 'Available Restock Inventory')->first();
if($checkRestockTask){
$checkUser = NotificationSettings::where('user_id', Auth::id())
->where('name', 'Available Restock Inventory')
->first();
if(!$checkUser){
NotificationSettings::create([
'user_id' => $user->id,
'name' => 'Available Restock Inventory',
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$data = [
'active' => 'settings',
'user_id' => $user->id,
'role' => $user->role_id ? $user->role_id : 'null',
'tasks' => $settings
]; //echo "<pre>"; print_r($data); echo "</pre>";
return view('notifications.index2')->with($data);
}
public function add ()
{
$data = array(
'active' => 'settings',
'user_id' => Auth::id(),
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return view('notifications.add')
->with($data);
}
public function saveNotification (Request $request)
{
$module = $request->get('module');
$user_id = $request->get('user_id');
$notification_name = $request->get('notification_name');
if($module == 1)
{
$module_name = 'Task Schedule';
}
$saved_notifs = NotificationSettings::where('user_id', $user_id)
->select('name')
->get();
$notif_names = array();
foreach ($saved_notifs as $saved_notif)
{
array_push($notif_names, $saved_notif->name);
}
if(in_array($notification_name, $notif_names))
{
return back()->with('error', 'Notification already added');
}
else
{
NotificationSettings::create([
'user_id' => $user_id,
'name' => $notification_name,
'module' => $module_name
]);
return redirect('notifications');
}
}
public function editNotification (Request $request, $user_id = null)
{
$checked_tasks = explode(',', $request->get('tasks'));
if(count($checked_tasks) > 0)
{
NotificationSettings::where('user_id', Auth::id())
->whereIn('name', $checked_tasks)
->update(['status' => 1]);
NotificationSettings::where('user_id', Auth::id())
->whereNotIn('name', $checked_tasks)
->update(['status' => 0]);
}
else
{
NotificationSettings::where('user_id', $user_id)
->update(['status' => 0]);
}
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
return json_encode($settings);
}
public function getTasks ()
{
$tasks = Tasks::select('name', 'id')
->orderBy('id')
->get();
$data = array(
'tasks' => $tasks,
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return $data;
}
public function viewAllNotifications ()
{
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
$data = array(
'active' => 'settings',
'notifications' => $notifications,
'user_id' => $user_id,
);
// return $data;
return view('notifications.all2')
->with($data);
}
public function getAllNotifications(Request $request){
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
return json_encode($notifications);
}
}
I just cant seem to get the number appear in the badge/pill that i have created. thanks for the answers in advance.
I am trying to get field name using with relation:
My Code:
public function getAllUsers()
{
$users = User::with('userBasicInfo','roles:name')->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}
when i simply use $users = User::with('userBasicInfo','roles)->get();
it returns my record accurately and when I used $users = User::with('userBasicInfo','roles:name')->get();
It returns my null array of roles I also want to display name using roles: name but it returns nothing.
You should try this:
public function getAllUsers()
{
$users = DB::table('users')
->select('users.name','roles.name')
->join('userBasicInfo', 'users.userbasicinfo_id', '=', 'userBasicInfo.id')
->join('roles', 'users.roles_id', '=', 'roles.id')
->get();
OR
$users = User::with(['userBasicInfo','roles:name'])->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}
Reference: How can I update an existing Eloquent relationship in Laravel 4?
$userinfo = \Userinfo::find($id);
\User::find($id)->userinfo()->associate($userinfo)->save();
I'm getting the error: Call to undefined method Illuminate\Database\Query\Builder::associate()
Here is the entire method:
public function saveUser($id)
{
$user = \User::find($id);
$userdata = \Input::all();
$rules = array(
'email' => 'required|email',
'state' => 'size:2',
'zip' => 'size:5',
'phone' => array('regex:/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/')
);
$validator = \Validator::make($userdata, $rules);
if ($validator->passes())
{
if ($userdata['email'] !== $user->email)
{
$rules = array('email' => 'unique:users');
$validator = \Validator::make($userdata, $rules);
if ($validator->fails()) return Redirect::route('admin.user.edit', array('user' => $user))
->with('error', 'Specified email already exists.');
}
$user->email = $userdata['email'];
$user->firstname = $userdata['firstname'];
$user->lastname = $userdata['lastname'];
$userinfoArray = array(
'address' => $userdata['address'],
'city' => $userdata['city'],
'state' => $userdata['state'],
'zip' => $userdata['zip'],
'phone' => preg_replace('/[^0-9]/', '', $userdata['phone'])
);
$user->save();
if (!$user->userinfo)
{
$userinfo = new \Userinfo($userinfoArray);
$userinfo = $user->userinfo()->save($userinfo);
}
else
{
$userinfo = \Userinfo::find($id);
\User::find($id)->userinfo()->associate($userinfo)->save();
//$user->userinfo()->update($userinfoArray);
}
return \Redirect::route('admin.user.detail', array('id' => $id))
->with('success', 'User updated.');
}
return \Redirect::route('admin.user.edit', array('id' => $id))
->withInput()
->withErrors($validator);
}
associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.
I am just guessing as you have not provided your eloquent model class code so can't see how you have set the relationships exactly, but if you have:
class User extends Eloquent {
public function userinfo()
{
return $this->hasOne('Userinfo');
}
}
class Userinfo extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
Then associate needs to be called against Userinfo as this has the belongsTo relationship to which the associate() method is attached.
For example
$user = \User::find(4);
$userinfo = \UserInfo::find(1);
$userinfo->user()->associate($user);
$userinfo->save();
Will set the foreign key user_id in the user_info table to the id of the $user object.
Looking at your above code it doesn't appear that this is what you are actually trying to do and that the
$user->userinfo()->update($userinfoArray);
call which you have commented out will in fact do what you seem to be trying to achieve, which is to update the userinfo that is related to the current user if that user already exists.
Hope this helps.
Glen
Change hasOne to belongsTo. It will look like:
class User extends Eloquent {
public function userinfo()
{
return $this->belongsTo('Userinfo');
}
}
class Userinfo extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
I was stuck on this problem for a few days and it ended up being quite simple to solve. I had created a folder called 'models' in my 'app' folder but I had forgotten to reconfigure my auth.php file.
This was my error.
Call to undefined method Illuminate\Database\Query\Builder
I fixed it by opening the auth.php in the config folder and changing the following line to include my models folder.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Foodie\User::class,
fix:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Foodie\Models\User::class,
Hope this helps!
You need to specify the field related like this:
public function profile()
{
return $this->hasOne('App\AdmProfile', 'id');
}