how to use php explode in laravel? - laravel

$user = $this->user;
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = $request['password'];
$user->save();
$name = explode(' ' ,$user->name);
$profile= $user->userdetail()->create([
'user_id' => $request->input('id'),
'first_name' => <the value of the first exploded string>
'last_name' => the value of the secondexploded string
]);
return redirect('confirmation');
}
how to split two words using explode function in php? For example i registered wth name of JOhn doe I want to create in my userdetail table the first_name of john and last_name of doe. How can i do it/

explode() returns an array of strings, so you can access elements by using keys:
$profile = $user->userdetail()->create([
'user_id' => $request->input('id'),
'first_name' => $name[0],
'last_name' => $name[1]
]);

You can use the following code
$full_name = "John Doe";
$name = explode(' ',$full_name);
$first_name = $name[0];
$last_name = $name[1];

Alternate way :
<?php
$ip = "fname lname";
$iparr = preg_split("/[\s,]+/",$ip);
echo "$iparr[0]";
echo "$iparr[1]";
?>
But explode is good(faster) than preg_split. ;)

Related

Laravel 7 : Why I am Getting Only First Array? I want to Fetch All Category ID data

I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.

Laravel Bulk Insert To Another Table From Selected Multiple Rows

I expected I can replicate multiple row from specific table to another table. But the problem, it cannot replicate password field data and spatie assignRole(). Whereas, all fields like email, name, username, etc are works properly.
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
$users = \App\Applicant::whereIn('id', $ids);
$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
$users = \App\User::insert($new_users);
//problem still lays here
//$users->assignRole('Applicant');
//$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
Trying to this approach but only insert one record
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
//$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
$users = \App\User::create([
'name' => $find_selected->name,
'username' => $find_selected->username,
'gender' => $find_selected->gender,
'email' => $find_selected->email,
'phone' => $find_selected->phone,
'password' => $find_selected->password,
'created_at' => $find_selected->created_at,
'updated_at' => $find_selected->updated_at,
]);
//problem lays here
$users->assignRole('Applicant');
$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
about password field , you need to make it visible with function like : makeVisible
for example:
$users->makeVisible('password')->toArray();
Edit 1:
about assignRole you must assign the role after you call the save() method
for example:
$users->password = $find_selected->password;
$users->save();
$users->assignRole('Applicant');
Edit 2:
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
//$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
foreach($find_selected as $new_users){
$user = \App\User::create($new_users);
$user->assignRole('Applicant');
}
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
i think the problem lays in this line:
$users = \App\User::insert($new_users);
insert method returns a boolean that indicate the insertion operation has succeeded or not ...
so you $users variable will hold a boolean value ...
and
$users->assignRole('Applicant');
$users->password = $find_selected->password;
wont work
you could use :
$find_selected->makeVisible(['password']);
foreach($find_selected as $user)
{
$newUser= new User();
$newUser->password = $user->password;
$newUser->save();
$newUser->assignRole('Applicant');
}

Laravel Socialite Facebook images are incorrect

I have a strange problem which I cannot figure out. I am using Laravel Socialite to allow login with Facebook account, there is a lot of users complaining that the profile image displayed on their account is incorrect, however the name etc is all fine.
It makes no sense to me as the name and the profile pic are pulled directly from FB at the same time.
public function socialUser(ProviderUser $providerUser)
{
$account = SocialFacebookAccount::whereProvider('facebook')->whereProviderUserId($providerUser->getId())->first();
if ($account) {
return $account->user;
} else {
$account = new SocialFacebookAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$user = User::whereEmail( $providerUser->getId() )->first(); // changed from getEmail to getId as FB doesnt always give an email
if (!$user) {
$profilePicName = md5(rand(1,10000)) . ".jpg";
$contents = file_get_contents( $providerUser->avatar_original );
Storage::disk('local')->put( 'profiles/' . $profilePicName, $contents );
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'profile_path' => $profilePicName
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
Instead of using md5, you can use the UUID generator. One of the reasons for this problem because md5 generates the same hash for the same input. for instance, when you pass md5(111) it'll generate 698d51a19d8a121ce581499d7b701668. so if for a different user you generate the same hash key, the latest image profile will take a place and the former will replace by the latter.
Scenario:
User1:
$profilePicName = md5(111) . ".jpg";
$contents = file_get_contents( $providerUser->avatar_original );
Storage::disk('local')->put( 'profiles/' . $profilePicName, $contents );
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'profile_path' => $profilePicName
]);
Scenario:
User2:
$profilePicName = md5(111) . ".jpg";
$contents = file_get_contents( $providerUser->avatar_original );
Storage::disk('local')->put( 'profiles/' . $profilePicName, $contents );
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'profile_path' => $profilePicName
]);
Now they both have 698d51a19d8a121ce581499d7b701668.jpg saved in their profile. And in this case the first user profile will be the same as the second user image profile.

Update profile function

I have a function that check updates the users profile info. Currently, if I put |unique:users in the validator every time I try to update the profile info on the form it will not let me because a user (which is me) has my email. So I figured out the unique means that nobody, including the current user can have the email that is being updated.
So I need to compare the current auth email to the one in the database. If it matches then it is ok to update the profile info. I know this is simple but I am not sure how to implement it and if that is the right logic.
So where in this code would I post if (Auth::user()->email == $email){..update email...} http://laravel.io/bin/GylBV#6 Also, is that the right way to do this?
public function editProfileFormSubmit()
{
$msg = 'Successfully Updated';
$user_id = Auth::id();
$user = User::find($user_id);
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$email = Input::get('email');
$phone_number = Input::get('phone_number');
$validator = Validator::make(Input::all(), array(
'email' => 'required|email',
'first_name' => 'required',
'last_name' => 'required',
'phone_number' => 'required'
));
if ($validator->fails()) {
return Redirect::route('edit-profile')
->withErrors($validator)
->withInput();
}else{
if(Input::hasFile('picture')){
$picture = Input::file('picture');
$type = $picture->getClientMimeType();
$full_image = Auth::id().'.'.$picture->getClientOriginalExtension();
if($type == 'image/png' || $type == 'image/jpg' || $type == 'image/jpeg'){
$upload_success = $picture->move(base_path().'/images/persons/',
$full_image);
if($upload_success) {
$user->picture = $full_image;
} else {
$msg = 'Failed to upload picture.';
}
}else{
$msg = 'Incorrect image format.';
}
}
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->phone_number = $phone_number;
$user->save();
return Redirect::route('invite')->with('global', $msg);
}
}
Worry not, Laravel has already considered this potential issue! If you take a look at the docs for the unique validation rule you'll see that it can take some extra parameters. As it happens, you can give it an id to ignore when looking at the unique constraint. So what you need to do is work out the id for the current model to update and pass that in. In the case of updating a logged-in user's profile it's made easy by Auth::id() as you already have in your code.
$rules = [
'email' => ['required', 'email', 'unique:users,email,'.Auth::id()],
'first_name' => ['required'],
// etc...
];
Obviously I chose to use the array syntax for validation rules there, but you can do the same with the pip syntax too. In a less specific system (create-or-add in a crud postSave type action) you can still do it by simply dong something like $model = Post::find($id) and then if $model is null you're creating and you just use 'unique' whereas if $model is not null, use 'unique:table,field,'.$model->getKey().

multiple where condition codeigniter

How can I convert this query to active record?
"UPDATE table_user
SET email = '$email', last_ip = '$last_ip'
where username = '$username' and status = '$status'";
I tried to convert the query above to:
$data = array('email' => $email, 'last_ip' => $ip);
$this->db->where('username',$username);
$this->db->update('table_user',$data);
How about using the where clausa status?
# must i write db->where two times like this?
$this->db->where('username',$username);
$this->db->where('status',$status);
I also tried this:
$this->db->where('username',$username,'status',$status);
you can use an array and pass the array.
Associative array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Or if you want to do something other than = comparison
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);
Yes, multiple calls to where() is a perfectly valid way to achieve this.
$this->db->where('username',$username);
$this->db->where('status',$status);
http://www.codeigniter.com/user_guide/database/query_builder.html
you can try this function for multi-purpose
function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
$ci->db->where($condition);
if($is_insert)
{
$ci->db->insert($table_name,$udata);
return 0;
}
else
{
$ci->db->update($table_name,$udata);
return 1;
}
}
$wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )";
$this->db->where($wherecond);
If you want to add AND and OR conditions at a time. this will work.
Try this
$data = array(
'email' =>$email,
'last_ip' => $last_ip
);
$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data);
it's late for this answer but i think maybe still can help, i try the both methods above, using two where conditions and the method with the array, none of those work for me i did several test and the condition was never getting executed, so i did a workaround, here is my code:
public function validateLogin($email, $password){
$password = md5($password);
$this->db->select("userID,email,password");
$query = $this->db->get_where("users", array("email" => $email));
$p = $query->row_array();
if($query->num_rows() == 1 && $password == $p['password']){
return $query->row();
}
}
you can use both use array like :
$array = array('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE' );
and direct assign like:
$this->db->where('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE');
I wish help you.

Resources