how to update an existing customer in laravel 5.2? - laravel-5

when i run this code a new row is inserted in the table.i want to update an existing customer in a row.
public function savepayment(Request $request,$amount)
{
$title ='Save Payment';
$payment = new Customer();
$payment ->paid = 'yes';
$payment->save();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'Amount Paid Successfully'));
return Redirect::action('Admin\CustomerController#paymentcustomer');
}

Try this
public function savepayment(Request $request,$amount)
{
$title ='Save Payment';
$payment = Customer::find('customer_id'); //need to find the customer before updating the existing customer
$payment ->paid = 'yes';
$payment->update(); //use update() instead of save()
Session::flash('flash_notification', array('level' => 'success', 'message' => 'Amount Paid Successfully'));
return Redirect::action('Admin\CustomerController#paymentcustomer');
}

Related

Laravel return value of updating a model

what I want to do is when the update is done, the data of the whole Model is returned.
I am registering and updating the database.
what i want when the data is updated i want it to return me all the data.
return response()->json($category);
the return returns 1, what I want to do is show the updated data instead of 1
$category = Category::where('id', $id)->update([
'title' => $request->title,
'slug' => $request->slug,
'is_home' => $request->is_home,
'language' => $request->language,
'status' => $request->status,
]);
return response()->json($category);
Create an instance of your object Category and save, that should work
$category = Category::find($id);
$category->title = $request->title;
$category->slug = $request->slug;
$category->is_home = $request->is_home;
$category->language = $request->language;
$category->status = $request->status;
$category->save();
return response()->json($category);
The return of the update() method is a boolean, not the object.

laravel 8 : send email verification after registration laravel

I'm building a laravel API. I want when i register , email verify will be sent activation code to user email automatically.
the problem is when i create a new activation code , i create a new record in tokens table too, this record has user_id field , so for store it , i use JWTAuth::user()->id but i have this error:
Trying to get property 'id' of non-object
i know why this happens , because I did not enter any tokens and i don't know how handle it and where to create a new record in tokens table
for more details I have :
AuthController : Login and register
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name'=>'required|string|min:3|max:30',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)],
));
$token = JWTAuth::fromUser($user);
dd($this->sendNotification());
$user->$this->sendNotification();
return response()->json([
'message' => 'successfully created',
'user' => $user,
'token' => $token,
], 201);
}
EmailVerifyController : for verify user email and validate activation code
public function emailVerify(Request $request){
$data = $request->validate([
'code' => 'required|size:10|numeric',
]);
$interedCode = (int)$data['code'];//convert code from string to integer
$userCode = Token::where('user_id' , JWTAuth::user()->id)->first();//find user from tokens table
$activationCode = $userCode->code; //get activation code of user in tokens table
$expires_in = (int)$userCode->expires_in; //get expire time of code
$now = Carbon::now()->timestamp;
if($interedCode == $activationCode) {
if ($now < $expires_in) {
$user = JWTAuth::user()->id;
$findUser = User::find($user);
$findUser->email_verified_at = Carbon::now()->timestamp;
$findUser->save();
$token = Token::where('user_id', JWTAuth::user()->id)->first();
$token->status = 1;
$token->save();
return response()->json('email verified successfully', 200);
} else {
return response()->json('code expired', 400);
}
}else{
return response()->json('wrong activation code' , 400);
}
}
SendNotificationTrait : for send email and create a new record in token table
trait EmailVerifyTrait
{
public function sendNotification(){
$random = $this->generateVerificationCode(6);
$details = [
'title' => 'Mail from ItSolutionStuff.com',
'body' =>$random,
];
Mail::to('*****#gmail.com')->send(new VerifyMail($details));
return response()->json([
'message'=>'your email verification code sent to your email'
] , 201);
}
public function generateVerificationCode($length = 6) {
$characters = '0123456789';
$charactersLength = strlen($characters);
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, $charactersLength - 1)];
}
$token = new Token();
$token->user_id = JWTAuth::user()->id;
$token->code = $code;
$token->status = 0;
$token->save();
return $code;
}
tokens tables : has this fields : user_id , code , created_at , expires_in
so how can i handle creating new Token record in tokens table ?
or should i use event listener ?
thank you for your help and sorry for my language.
for handle this email verification , i used laravel Notification : https://laravel.com/docs/8.x/notifications
and i used $user->id for getting id and use it for user_id field in tokens table.
codes:
Register method
use ActivationCode;
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name'=>'required|string|min:3|max:30',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
//create user
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)],
));
//create token
$token = JWTAuth::fromUser($user);
//create a new activation code
$activationCode = $this->generateVerificationCode();
//create a new token
$newToken = new Token;
$newToken->code = $activationCode;
$newToken->status = 0;
$newToken->user_id = $user->id;
$newToken->save();
//email details
$details = [
'greeting' => 'Hi'.$request->name,
'body' => 'use this activation code for verify your email address',
'activation_code'=>$newToken->code,
'thanks' => 'thank you',
'order_id' => 101
];
//send email verify to user email
Notification::send($user, new EmailVerification($details));
return response()->json([
'message' => 'use created successfully and activation code sent to email',
'user' => $user,
'token' => $token,
], 201);
}
Activation code trait:
trait ActivationCode
{
public function generateVerificationCode($length = 6) {
$characters = '0123456789';
$charactersLength = strlen($characters);
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, $charactersLength - 1)];
}
return $code;
}
}
EmailVerify Notification :
class EmailVerification extends Notification
{
use Queueable;
private $details;
public function __construct($details){
$this->details = $details;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->greeting($this->details['greeting'])
->line($this->details['body'])
->line($this->details['thanks'])
->line($this->details['activation_code']);
}
public function toArray($notifiable)
{
return [
'order_id' => $this->details['order_id']
];
}
}

what could be wrong as there is no error displayed and the code isn't processed: enum in Laravel

Migration
In my migration, I have following passed to the database
$table->enum('product_name', ['chocolate', 'Candy','biscuits', 'Berry']);
$table->string('description');
$table->string('product_no');
$table->timestamps();
in my model I have this below the fillable and a function to select a choice.
protected $fillable =[
'product_no','description'
];
protected $product_name = ['chocolate', 'Candy','biscuits', 'Berry'];
public function getProduct_name()
{
return $this->product_name;
}
The problem is I don't know how to handle this in controller and Postman. It is not displaying any error
public function store(Request $request)
{
$this->validate($request, [
'product_no' => 'nullable|product_no',
'description' => 'required|string',
]);
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->products()->save($product))
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'product could not be added'
], 500);
}
What I intend to achieve is to create a front-end in Angular with a drop down to select the product_name (from the list hard-coded) and description and product_no are fillable. However from Postman, I just entered the values for the three fields i.e. product_name, description and product_no
It seems you forgot to replace method and variable names when you copy the votes code
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->votes()->save($vote))
--------------------^^^^^^^-------^^^^^--
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
That should be
if (auth()->user()->products()->save($product))
Also there is another field (product_name) that you're trying to save but it's not fillable.
protected $fillable =[
'product_no','description', 'product_name'
];
And also, you may want to consider that using same pattern when naming your variables and methods. You can say getProductName or get_product_name instead of getProduct_name.

Manually Passing a Foreign key Value

I can not pass a foreign key value (which is user_id) to my newly created article.
Here is my code...
<?php
if (is_null($request->user_id)) {
$request->user_id = $user->user_id;
}
$request->validate(['title' => 'Required|string|min:3', 'body' => 'Required|string|min:5', 'user_id' => 'Required|exists:users,user_id']);
if ($article = Article::create($request->all())) {
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
} else {
return 'Article could not be created';
}
Change this:
if($article = Article::create($request->all())) {
$article->user_id = $request->user_id;
$article->save();
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
}
Try this,
public function store(Request $request)
{
$request->validate([
'title' => 'Required|string|min:3',
'body' => 'Required|string|min:5',
]);
$data = $request->all();
//you don't need to validate user_id is correct
//if you are using auth middleware in the route
$user = auth()->user()
$data['user_id] = $user->id
if ($article = Article::create($data)) {
event(new ArticleCreated($user));
return response()->json([
'success' => true,
'reason' => 'Article Created successfully',
$article
]);
} else {
return 'Article could not be created';
}
}
Hope this helps
Check your fillable array in Article model, there must be user_id, and check if the user id is passed in the $request->all().

How to call the form fields in a route file in laravel

Give me an idea to call the form fields and controller in the route file and store them into the WHMCS i.e., add the client details to WHMCS. Find below the Route along with the form fields.
Route::get('/create', function () {
$users = Whmcs::AddClient([
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
'email' => Input::get('email'),
'address1' => Input::get('address1'),
'city' => Input::get('city'),
'state' => Input::get('state'),
'postcode' => Input::get('postcode'),
'country' => Input::get('country'),
'phonenumber' => Input::get('phonenumber'),
'password2' => Input::get('password2'),
'responsetype' => 'json',
]);
return $users;
});
Find below the controller code
class ClientController extends Controller
{
public function insertform(){
return view('clientlayout.main.signup');
}
public function create(){
$firstname = trim(htmlentities($_POST["firstname"]));
}
}
Perhaps the following may help point you in the right direction:
Adapt to your requirements and place inside your controller.
public function createUser($request)
{
//Create user
$newUser = new User;
$newUser->username = $request->username;
$newUser->first_name = $request->first_name;
$newUser->last_name = $request->last_name;
$newUser->email = $request->email;
$newUser->password = bcrypt($request->password);
$newUser->last_login_at = Carbon::now();
$newUser->save();
//Manually assign the role_id so no escalating privileges.
$newUser->assignRole('user');
return $newUser;
}
First of all you have to follow MVC method in laravel
Route
Route::match(['get','post'],'/create', 'ControllerName#functionname');
controller
public function create(Request $request){
$id = modelname::modelfunctionname($request->Input());
print "<pre>";
print_r ($request->input());
print "</pre>"; exit;
}
$request->input() you will get the form fields
In Your model
public static function modelfunctionname($input){
$create = DB::table('admins')->insertGetId(array(
'firstname' => $input['firstname'],
'lastname' => $input['lastname']
like this Do it for remaining field
));
return $create;
}

Resources