Laravel exclude current user from array - php

Logic
I have store function and it's returning data of users in the group.
The person who saves this data is also included of group users.
Now I want to exclude s/he from group users when data returns.
code
I've commented the code so you can understand it better.
public function store(Request $request)
{
$user = $request->user(); // current user who should be excluded
$group = Group::where('id', $request->input('group_id'))->first();
$message = new GroupMessage;
$message->group_id = $request->input('group_id');
$message->user_id = $user->id;
$message->note = $request->input('newMessage');
$message->message_id = $request->input('message_id');
$message->save();
// returning data
// 'user' is current user (also available in 'group.users')
// remove current 'user' from ('group.users')
$ms = GroupMessage::where('id', $message->id)->with(['user', 'group', 'group.users'])->first();
return response()->json([
'data' => new NotesResource($ms),
'message' => 'Message sent successfully.'
], 200);
Log::info('message data sent.');
broadcast(new MessageSent($message))->toOthers();
}
Screenshot
here is how code above returns data
Any idea?

You can exclude this User using Eager Loading Constraints:
$ms = GroupMessage::where('id', $message->id)
->with(['user', 'group.users' => function ($query) use ($user) {
$query->where('users.id', '<>', $user->id);
}])->first();
Laravel 7.x Docs - Eloquent - Relationships - Constraining Eager Loads

Related

Laravel Auth::user()->name and Auth::user()->id is not working

Hi im storing data in database but when i use Auth::user()->name it is not working. in my other controller its working. But when i hard coded the name and the id it works. I already imported auth and still get the same issue. Thanks for the help. this is weird .
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ForumPost;
use Auth;
public function create_discussion(Request $request){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = Auth::user()->name;
$create->comment_frequency = 100;
$create->user_id = Auth::user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}
btw im using vue as a front-end.
You need to import/add
use Auth;
use App\User;
Than save logged in user as this in your controller:
public function create_discussion(Request $request, $id){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = auth()->user()->name;
$create->comment_frequency = 100;
$create->->user_id = auth()->user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}
This is from Laravel 7.14. You are not passing the id in your function.
You can Use in your controller
get User to your controller.. user auth in your controller head.
use Auth;
use App\User;
Get User id from :
Auth::id();
Get User Name from
Auth::user()->name;
If you are not authenticed user, then Auth::user()->id won't work.
Do a Auth::check() before, to be sure that you are well logged in :
public function create_discussion(Request $request){
if(Auth::check()){
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = Auth::user()->name;
$create->comment_frequency = 100;
$create->user_id = Auth::user()->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
} else {
return response()->json([
'message' => 'You are not authentic user. '
]);
}
}
Before creating a forum you can do an auth()->check()
if(auth()->check()){ //returns true or false
$user = auth()->user();
$create = new ForumPost ;
$create->post_content = $request->content;
$create->user_name = $user->name;
$create->comment_frequency = 100;
$create->user_id = $user->id;
$create->save();
return response()->json([
'message' => 'Discussion created successfully '
]);
}else{
return response()->json(['message'=>'not authenticated could not create a forum.']);
}
may be this will work.
be sure that you are logged in.
and use that
auth()->user()->name;
auth()->id();
it's the same.
if error 500 , check the .env is exists then try
php artisan key:generate
php artisan cache:clear
php artisan config:clear
I manage to get it working by creating a props and pass it to my post request. I dont know why that auth()->user()->.... is not working.I think this will be a problem when the proj. is getting larger. Thanks for the answers

User::where(user->id==$profile->id); get profile that is equal to user in controller

If you set relation ships between the User.php return $this->belongsTo('App\User'); and Profile.php return $this->hasOne('App\Profile', 'user_id', 'id'); how can u get a corresponding user to the profile when you only get the Profile variables. public function update(Request $request, Profile $profile)
i was thinking of something like this User::where(user->id==$profile->id); but its not working how would can you do it?
mine hole function:
if(\Auth::check()) {
if(\Auth::user()->type == 'admin'){
$validated = $request->validate([
'username' => 'required',
'email' => 'required|email',
'firstname' => 'required',
'lastname' => 'required',
'age' => 'required|numeric|max:150',
'birthdate' => 'required|numeric',
'bio' => 'required|min:30',
'select_file' => 'image|mimes:jpg,png,gif,jpeg|max:2048'
]);
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$profile->username = $validated['username'];
$profile->email = $validated['email'];
$profile->firstname = $validated['firstname'];
$profile->lastname = $validated['lastname'];
$profile->age = $validated['age'];
$profile->birthdate = $validated['birthdate'];
$profile->bio = $validated['bio'];
$profile->image_path = $new_name;
$profile->update();
$user = User::where(user->id==$profile->id);
$user->name = $validated['username'];
$user->email = $validated['email'];
$user->update();
return redirect()
->route('admin')
->with('succes', 'Profile updated succesfully');
} else {
return redirect()
->route('admin')
->with('fail', 'Profile is unable to be update successfully');
}
} else {
return redirect()
->route('login')
->with('fail', 'Profile is unable to be update successfully
because ur not an Admin');
}
Your where is not formatted properly. You need to pass in 2 (or 3) parameters, where the first is the column, and the second is the value you're checking for. If using 3 parameters, the second would be the operator (= or !=). Don't forget first() (for one record) or get() (for a collection of records), so that the query actually runs. Otherwise, it will just be the QueryBuilder object.
User::where('id', $profile->user_id)->first();
or
User::where('id','=', $profile->user_id)->first();
Since you're checking against the user's id, you can also use find() to get one record:
User::find($profile->user_id);
You can do it some ways.
Solution 1:
User::whereId($profile->user_id)->first();
Solution 2:
User::where('id', $profile->user_id)->first();
Solution 3:
User::where('id','=', $profile->user_id)->first();
Solution 4:
User::where(['id' => $profile->user_id])->first();
Also you can do it
In Profile model define
public function user()
{
return $this->belongsTo('App\User');
}
Than you can lazy load
$user = $profile->load('user')->user; // but it is lazy loading

Laravel 5.5 Check User exist with three param in two tables

I develop the register module , i want to check users registered in my web app with email , nationalCode or mobile , i have two tables , users and userInfo , i store email in users table and i store nationalCode and mobile in userInfo table , i want to write code to detect if email or nationalCode or mobile of the user exist in my two tables , i show warning text that user have registered in my site, please help me to do this job,
I use step form and i write ajax to call method to do this task,
note that it may be possible teh user have three matches or just one of them is matched
thanks for your helps :)
Here is the ajax code :
$.ajax({
url: url',
type: 'POST',
data: {
_token: CSRF_TOKEN ,
code:code,
email:email,
mobile:mobile,
},
dataType: 'JSON',
success:function(data) {
//return data
}
});
and here is my method is controller
public function checkUser(Request $request)
{
$email = $request->email;
$mobile = $request->mobile;
$code = $request->code;
//here the query to detect user exist with three params
}
Let's say you have your relationships defined as follows:
class User extends Model
{
public function info()
{
return $this->hasOne(UserInfo::class);
}
}
class UserInfo extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
... then you can check the existence of this user with something like this.
$user = User::where('email', $request->email)
->whereHas('info', function($query) use($request) {
$query->where('mobile', $request->mobile)
->where('code', $request->code);
})
->exists();
// user will be false if there's no record matching those parameters
Alternatively, if you don't have your relationships defined, then you probably need to do something like this instead.
$user = User::where('email', $request->email)->exists();
$info = UserInfo::where([
'mobile' => $request->mobile,
'code' => $request->code
])->exists();
if($user && $info) {
// user exists
}
I would still prefer to go with option one :)
If you put unique identifier in you table, database will automatically detect it and return the error, but its not good practice to let database to handle that,
If you want to use Eloquent then the query would look like this
public function checkUser(Request $request)
{
$email = $request->email;
$mobile = $request->mobile;
$code = $request->code;
$user = User::query()->where('email', '=', $email)->orWhere('mobile','=',$mobile)
->orWhere('code', '=',$code)->get();
if($user) {
// User already exits
return;
}
}
But this validation for me is not good, Better is to use Laravel Requests
https://laravel.com/docs/5.7/validation#form-request-validation
To generate custom request use this command (php artisan make:request RequestName)
public function rules()
{
return [
'title' => 'required|unique:users',
'mobile' => 'required|unique:users',
'code' => 'required|unique:users',
];
}
Using the request is simple
public function checkUser(YourCustomRequest $request)
{
// Laravel will take care of all fields and check them if they exist in the database
}

How to stop Auth user from visiting own page with non auth user privileges in laravel?

My laravel application is a social media site. Here's the route for visiting another laravel user's profile
Route::get('/dashboard/{id}', [
'uses' => 'UserController#getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);
It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.
Here's the controller:
public function getProfile($id)
{
if(Auth::user() === $id)
redirect('dashboard');
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6);
return view('profile.index',compact('user','posts', 'photos'));
}
I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?
You get user instance by Auth::user() not only the user ID. You are comparing instance with the numeric value. It will not work. You have to use Auth::id() or Auth::user()->id in order to get ID of the logged in user. The following code will work in your case.
public function getProfile($id)
{
if(Auth::id() == $id)
{
redirect('dashboard');
}
else
{
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6);
return view('profile.index',compact('user','posts', 'photos'));
}
}
Let me know if it helps!
You try to compare the current user object to the request id, try this code:
public function getProfile($id)
{
if(Auth::id() === $id) {
redirect('dashboard');
}
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6)
return view('profile.index',compact('user','posts', 'photos'));
}

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
In laravel eloquent, has default exists() method, refer followed example.
if (User::where('id', $user_id )->exists()) {
// your code...
}
One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.
if($user->isEmpty()){
// has no records
}
Eloquent uses collections.
See the following link: https://laravel.com/docs/5.4/eloquent-collections
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
if (User::where('email', 'user#email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first(), not count() if you only need to check for existence.
first() is faster because it checks for a single match whereas count() counts all matches.
It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.
$result = User::find($email)->exists();
If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e
Call to a member function exists() on null.
But the case is different for where() thing.
$result = User::where("email", $email)->exists();
The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
In your Controller
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
In your View - Display Already Exist Message
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
would work with try/catch
->get() would still return an empty array
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Simple, comfortable and understandable with Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
I solved this, using empty() function:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
you have seen plenty of solution, but magical checking syntax can be like,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
can be written as
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user exist!
}else{
// user does not exist
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
If you want to insert a record in the database if a record with the same email not exists then you can do as follows:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.
You can check out the docs here: Laravel upserts doc
You can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But also you can use these ways:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
Note :: Where condition according your requirements.
Simply use this one to get true or false
$user = User::where('email', '=', Input::get('email'))->exists();
if you want $user with result you can use this one,
$user = User::where('email', '=', Input::get('email'))->get();
and check result like this,
if(count($user)>0){}
Other wise you can use like this one,
$user = User::where('email', '=', Input::get('email'));
if($user->exists()){
$user = $user->get();
}
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";

Categories