I am using Select2 for create multiple data in database.
My Languages Field In Database:
English,French,Spanish
My Controller
public function store(UserCreateRequest $request)
{
$data = $request->all();
$data['languages'] = implode(',', $request['languages']);
User::create($data);
return redirect()->back()->with('message', 'Account Successfully Created');
}
But After Update The language field changes as follows
["English","French","Spanish"]
Update in controller
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$user->update($request->all());
return redirect()->back()->with('message', 'Account Successfully Updated');
}
I'm Using in_array() in edit Form For Showing Selected Data
You can create one methods, or rewrite you'r update methods
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$data = $request->all();
$data['languages'] = implode(',', $request['languages']);
$user->update($data);
return redirect()->back()->with('message', 'Account Successfully Updated');
}
But I think batter create relation user -> manyToMany -> language, table example
user {user_id, email, password}
user_language {user_language_id, user_id, language_id}
language {language_id, key, title}
For select get all from language.
For attach language to user use attach method. For get all language just call ->languages on user. And etc. Sorry for my English I hope you understand me.
Related
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
I have to save data in a database table with userid using laravel ajax. Can anyone please help me to solve this issue
my controller code
public function store(Request $request)
{
$rearcameras = new Rearcameras();
$rearcameras->user_id = auth()->id();
$rearcameras->name = $request->name;
$rearcameras->size = $request->size;
$rearcameras->type = $request->type;
return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
}
and the response it getting is
{"success":true,"data":{"user_id":null,"name":null,"size":null,"type":"f-camera"},"message":"Command Send Successfully successfully."}
I have to save logged userId on submitting....I'm getting user_id null how can I store user_id please help me.
Thanks in advance
Update your controller code
public function store(Request $request)
{
$rearcameras = new Rearcameras();
$rearcameras->user_id = Auth::user()->id;
$rearcameras->name = $request->name;
$rearcameras->size = $request->size;
$rearcameras->type = $request->type;
$rearcameras->save();
return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
}
Don't forget to use use Auth at the top of the controller
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
}
A simple question: how do I modify (hash) the request value before saving it with Laravel Backpacker CRUD admin?
As far as i understand, it should be done somewhere before these methods are executed in the crud controller:
public function store(StoreRequest $request)
{
return parent::storeCrud();
}
public function update(UpdateRequest $request)
{
return parent::updateCrud();
}
but I have no idea how to do it correctly.
Edit: the request is not a Request object, but rather StoreRequest or UpdateRequest that looks something like this:
Fix:
public function update(UpdateRequest $request)
{
// Hash password before save
if (!empty($request->password)) {
$request->offsetSet('password', Hash::make($request->password));
}
return parent::updateCrud($request); // <-- Pass the modified request, otherwise the CRUD reads it again from post data
}
You can update $request values using the offsetSet method
$request->offsetSet('name', $newName);
Edit: To update user password you can do something like this:
public function update_password(Request $request)
{
$user = User::find(Auth::user()->id);
if (Hash::check($request->old_password, $user->password)) {
$user->fill([
'password' => Hash::make($request->password)
])->update();
return redirect()->back()->with('message' => 'Your password has been updated.');
}
else {
return redirect()->back()->with('message' => 'The password entered do not match our records.');
}
}
I did not check the code but it should work. Now update it to your needs.
If you're asking about how to modify data in $request variable, you can just do this:
$request->property = 'New value';
Also, you can add data to reuqest itself (not into variable):
request()->request->add(['key' => 'value']);
I am new to laravel.I have a controller called userController to mangae user in my application.Here i have a user authentication and profile system.It will send the user to its own profile after login.Sometimes user may wish to search for a random username or id field in the url to search for a user.If desired user is found ,their profile info will be shown in the profile section.But if no user is found i want my application to get the current logged in user and show his/her info instead.How i can do that?
if my user name is 'zim' i can write the url mydomain/user/zim ,it will get my profile,But if i search an invalid name say 'zi' mydomain/user/zi , i want my application to return mydomain/user/zim again
All i can manage here is to show a flash message if no user is found.Can't figure out how to retrieve the current logged user.Tried to use the Request class but seems not working
loginUser function():
public function loginUser(Request $request){
$data = $request->all();
$rules = array(
'name' => 'required',
'password'=>'required'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if($validator->fails()){
$errors=$validator->messages();
return redirect()->back()->withErrors($validator);
}else{
if(Auth::attempt(['name'=>$request['name'],'password'=>$request['password']])){
return redirect()->route('user.show',[$request['name']]);
}else{
return redirect()->back()->with('data', 'wrong username or password');
}
}
}
show() method in userController:
public function show($user,Request $request) // tried with Request but failed
{
//
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if($info){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user');
return View::make('user.show');
}
}
You just need to change your show method slightly.
public function show($user,Request $request)
{
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if(empty($info)){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user but here is your info :)');
return View::make('user.show')->with('user', Auth::user());
}
}
Edited for better logic.
public function show($username)
{
$info = userModel::where(username, $username)->get()->first();
if($info != null){
return View::make('user.show')->with('user', $info);
}
else{
session()->flash('message','No user found! But here is your info!');
return View::make('user.show')->with('user',Auth::user());
}
}
Here is a much simplified option. (Always allow the URL to collect only one type instead of checking if its id or username)