Laravel profile edit - laravel

Alright , I have used this way to save the users info and It works perfect,
static public function memberSave($request) {
$signup = false;
$member = new Members();
$member->name = $request['name'];
$member->email = $request['email'];
$member->password = bcrypt($request['password']);
$member->save();
if (!empty($member->id)) {
$new_id = $member->id;
DB::insert("INSERT INTO roles VALUES ($new_id, 5613)");
$signup = true;
Session::flash('sm', 'Thank you! You have signed up successfully!');
}
return $signup;
}
but when making this for editing the profile(by user) It doesn't work
becuase I use new(); (making object)
I also didn't succeed to use find(); so I tried to use this
static public function saveProfile($id,$name,$email,$password) {
$sql = "UPDATE members SET name=?,email=?,password=? WHERE id=?";
$member = DB::select($sql, [$name,$email,$password,$id]);
but when I want to bcrypt the password in laravel doesnt work .
this is the code also in the second page
public function postProfile(ProfileValidation $request) {
if (Members::saveProfile($request['id'], $request['name'], $request['email'], $request['password'])) {
return redirect('');
}
}
I hope getting helped for editing the users profile by laravel , thanks.

Your Members class must extend Eloquent\Model for following this code to work.
class Members extends Model {
// optional
protected $table = 'members';
...
To find and update the member using email,
// find the single member
$member = Members::where('email', request['email'])->first();
// update the member
$member->name = $request['name'];
$member->password = $request['password'];
// now save the updated member
$member->save();
In order to to encrypt Password, Laravel provides Hash Facade,
// import this
use Hash;
...
// encrypt Password
$encrypted = Hash::make($request['password']);
...

if you want your user automatically hash the password at your model put:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
and you can directly check for the user if exist create new or update it:
public function saveMember($request)
{
$member = Member::findOrNew($request->email);
//All your input you want to save
$member->save();
}

Related

Find user by name and surname in USER collection

This is my code:
public function search_clients($names){
$user = Auth::user();
$all_clients = $user->clients; // Retrieve object of all clients of user
$names = ["Pera","Peric"]; // Pera - name, Peric - surname
$collect = collect($all_clients);
$klijenti = $collect->filter(function($query) use ($names){
$query->whereIn('name', $names);
$query->orWhere(function($query) use ($names) {
$query->whereIn('surname', $names);
});
return $query;
});
return $klijenti;
}
I want to search in object for name and surname and return it. Like if I have 100 users in $all_clients, i want to return only users name or surname LIKE "PERA" or "PERIC".
Currently it is returning everyone.
An option would be to define a search scope on the Client model
class Client extends Model
{
public function scopeSearch($query, $searchTerm)
{
$query->where("name", "ilike", "%$searchTerm%")
->orWhere("surname", "ilike", "%$searchTerm%");
}
//rest of the code
}
Then in the controller method you can use the scope
public function search_clients($names)
{
$user = auth()->user();
$all_clients = $user->clients()->search($names)->get();
return $all_clients;
}

How to retrieve hidden property form a relationship model

i have 3 models: Order, Lancenter and ClientAccount
Lancenters can create Orders.
ClientAccounts stores username and password.
When an order is created, the Lancenter can choose an existant client account or create a new one, so i show up all ClientAccounts related with the current Lancenter.
For security reasons, i don't retrieve the ClientAccount password when a lancenter wants to create a new order.
So, in ClientAccount.php i have this:
protected $hidden = ['password'];
And in Lancenter.php:
public function client_accounts()
{
return $this->hasMany('App\ClientAccount', 'id_lancenter');
}
In LancenterController.php this function retrieves lancenter's client accounts without the password:
public function getClientAccounts()
{
$lancenter = Lancenter::with('client_accounts')->where('id_owner', Auth::id())->first();
return response()->json(['client_accounts' => $lancenter->client_accounts]);
}
The problem is that the created order belongs to a ClientAccount and in this case i need to retrieve also the password of ClientAccount.
So i have in Order.php:
public function client_account()
{
return $this->belongsTo('App\ClientAccount', 'id_client_account');
}
And this function in OrderController.php retrieves new orders:
$orders = Order::with('client_account')->where('status', $status)->get();
return response()->json(['orders' => $orders]);
Obviously, the ClientAccount is retrieved without the password.
I get it by doing a loop to get the ClientAccount of each order in the index function in OrderController, but i supose that there is a cleaner to do it. Hope you can help me.
Update:
this is the loop in OrderController that i'm talking about
public function index($status)
{
$orders = Order->where('status', $status)->get();
foreach($orders as $key => $order) {
$client_account = ClientAccount::find($order->id_client_account)->makeVisible('password')->toArray();
$orders[$key]['client_account'] = $client_account;
}
return response()->json(['orders' => $orders]);
}

how to view order submitted by customer to the seller?

A customer can post an order to the seller. The problem is how can seller(ps) can view his order.Because each order may be submitted to different seller.
SLotController.php
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = ? // i dont know how to get seller id
$slotorder->save();
return view('home');
}
User model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
SlotOrder model
public function user()
{
return $this->belongsTo('User::class');
}
public function user()
{
return $this->belongsTo('Ps::class');
}
Ps Model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
Update
After user click make an order, it will go to this page according to their id. For this screenshot the id for the seller is 1. So back to my question , how can i get the seller id when user submit the order. Therefore he can view the order in his dashboard.
You are using a get route, which uses the seller id, so in the method which handles this route send the variable to the view, example:
Route
Route::get('giveorder/{seller_id}',Controller#method);
Controller Method
public function method($seller_id){
return view('giveorder',compact('seller_id'));
}
Create a hidden input inside your form:
<input type="hidden" value="{{$seller_id}}" name="seller_id">
So now you can use this seller_id in your order method:
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = $request->seller_id;
$slotorder->save();
return view('home');
}

Symfony lost session on Service

I have a UserProvider for the Lexik bundle and check if the user exists through the session but there is a problem when I make certain request the sessions lose the value someone knows because this happens.
Service
app.user_provider:
class: ApiBundle\Security\Userprovider
arguments: ["#session","#switchconnection","#doctrine.orm.entity_manager" , "#doctrine.dbal.default_connection" , "#doctrine"]
My provider
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use ApiBundle\Entity\Utilizador;
use Symfony\Component\HttpFoundation\Session\Session;
public function __construct(Session $session,$switchconnection ,\Doctrine\ORM\EntityManager $em , \Doctrine\DBAL\Connection $dbalConnection , \Doctrine\Bundle\DoctrineBundle\Registry $doctrine) {
$this->session = $session;
$this->switchconnection = $switchconnection;
$this->em = $em;
$this->connection = $dbalConnection;
$this->doctrine = $doctrine;
}
public function loadUserByUsername($username)
{
if($this->session->get("currentuser") == $username){
$this->switchconnection->switchDatabase($this->session->get("dbconnection"), $this->connection , $this->doctrine);
$conn = $this->em->getConnection();
$stmt = $conn->prepare(".....");
$stmt->bindParam(1, $username);
$stmt->execute();
$results = $stmt->fetchAll();
$count = count($results);
if($count != 0)
{
$user= new Utilizador();
$user->setUsername($results[0]['username']);
$user->setEmail($results[0]['email']);
return $user;
}
}
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username) );
}
I also checked that in the var/session/dev folder there is a session register with 2 Phpsession almost identical.
Update 1
Important information this only happens in webkit browsers
Please include session component in your ApiBundle\Security\Userprovider.
use Symfony\Component\HttpFoundation\Session\Session;
I think you forgot to add session component.
Update-1
User service_container by passing it in service. For me its working fine.
services.yml
app.user_provider:
class: ApiBundle\Security\Userprovider
arguments: ["#service_container", "#session","#switchconnection","#doctrine.orm.entity_manager" , "#doctrine.dbal.default_connection" , "#doctrine"]
Provider
protected $container;
protected $session;
public function __construct($container, Session $session,$switchconnection ,\Doctrine\ORM\EntityManager $em , \Doctrine\DBAL\Connection $dbalConnection , \Doctrine\Bundle\DoctrineBundle\Registry $doctrine) {
$this->container = $container;
$this->session = $container->get('session');
}

How to cache model attributes in Laravel

In my current configuration, a user's email is stored on a remote server that I need to hit with a curl quest.
Luckily, I only need the email once a day when a certain process runs. However, when that process does run it will need to reference the email multiple times.
This is the current accessor I have set up for email. The problem is the curl request is being called every time I use $user->email. What's the best way to avoid this?
in UserModel:
public function getEmailAttribute(){
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
private $cached_email = false;
public function getEmailAttribute(){
if ($this->cached_email){
// if set return cached value
return $this->cached_email;
}
// get the email
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
// cache the value
$this->cached_email = $response->email;
// and return
return $this->cached_email;
}
Depending on your use case make adjustments (ie. session, cache , static property...).
Extend a the Eloquent Model class
namespace App\Models\Utils;
use Illuminate\Database\Eloquent\Model as OldModel;
class MyModel extends OldModel
{
private $cachedAttributes = [];
public function getCachedAttribute(string $key, Callable $callable)
{
if (!array_key_exists($key, $this->cachedAttributes)) {
$this->setCachedAttribute($key, call_user_func($callable));
}
return $this->cachedAttributes[$key];
}
public function setCachedAttribute(string $key, $value)
{
return $this->cachedAttributes[$key] = $value;
}
public function refresh()
{
unset($this->cachedAttributes);
return parent::refresh();
}
}
make your class
class ElementWithEmail extends MyModel
{
const ATTRIBUTE_KEY_FOR_EMAIL = 'Email';
public function getEmailAttribute(){
$key = self::ATTRIBUTE_KEY_FOR_EMAIL;
$callable = [$this, 'getEmail'];
return $this->getCachedAttribute($key, $callable);
}
protected function getEmail()
{
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
}
Call it from your code
$element = new ElementWithEmail();
echo $element->email;

Resources