Single column not being updated in laravel 5 - laravel

I am tying to update a single column of a table messages and I have the following code:
public function messageSeen(Request $request){
$data = Message::find($request->id);
$success = Message::where('id', $request->id)->update(array('is_seen' => 1));
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?
I tried the other way like the following:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
dd($result->message);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result->message;
$data['user_id'] = $result->user_id;
$data['conversation_id'] = $result->conversation_id;
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
But here I am getting unexpected thing with this method. Here I am being able to do dd($result) and being able to get data like this:
#attributes: array:9 [
"id" => 22
"message" => "How are you?\r\n"
"is_seen" => 0
"deleted_from_sender" => 0
"deleted_from_receiver" => 0
"user_id" => 2
"conversation_id" => 1
"created_at" => "2019-09-29 03:42:39"
"updated_at" => "2019-09-29 03:42:39"
]
however, if I tried to do dd($result->message) then I get null! What am I doing wrong?
I tried the following code:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result[0]['message'];
$data['user_id'] = $result[0]['user_id'];
$data['conversation_id'] = $result[0]['conversation_id'];
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
and it worked but instead of updating it is adding new column when the message is seen. But first I don't understand why do I have to do $result[0]['key'] in the first place.

You need to specify which fields in your table can be mass assigned, by adding or updating the $fillable property of your model:
protected $fillable = [..., 'is_seen', 'message', ...];
This is required for the create() and update() methods, as those accept "mass" variables in the array you pass in. Whereas with save() you have to manually, explicitly, assign the properties on the model, so there is no risk of accidentally saving something you didn't mean to. And this is exactly the behaviour you are seeing - update() is not working, but save() is.

You should try this
public function messageSeen(Request $request) {
$input = Request::all();
$data = Message::find($input['id']);
if (!empty($data)) {
$update = array();
$update['is_seen'] = 1;
$success = Message::where('id', $input['id'])->update($update);
if ($success) {
return response()->json(['status' => 'success'], 200);
} else {
return response()->json(['status' => 'Something went wrong'], 400);
}
} else {
return response()->json(['status' => 'Data not updated'], 404);
}
}
Value depends on data type of is_seen are string or integer

Related

Object of class Illuminate\Routing\Redirector could not be converted to string. srmklive/laravel-paypal

I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.

How to update 2 table data using query builder

I have problem with edit and update with 2 table using query builder.
--->After i press button submit--->the data insert new row---> not update current data.
This is my function edit(only for view old data)
public function edit(Request $request, $id){
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$country = Country::all();
$geo_zones = GeoZone::all();
//dd($tax_rate);
//dd($tax_rate_details);
//dd($geo_zones);
if(!$tax_rate) {
return redirect('/');
}
return view('tax_management.edit',['country' => $country , 'tax_rate'=>$tax_rate , 'geo_zones'=>$geo_zones, 'tax_rate_details'=>$tax_rate_details]);
}
This is my update(i do validation and the saveTax is the saving part)
public function update(Request $request, $id){
$this->validate($request,[
'country_id'=> 'required',
'tax_type' => 'required',
'name' => 'required|max:100',
'code' => 'required|max:50'
]);
//dd($request->input());
DB::beginTransaction();
try{
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$this->saveTax($request, $tax_rate);
DB::commit();
return redirect()->route('tax_management.index');
} catch (\Exception $ex){
//dd($ex);
DB::rollback();
return back()->withInput()->withErrors('Fail to save');
}
}
This is my function save()
private function saveTax(Request $request, $tax_rate){
$tax_rate->country_id = $request->input('country_id');
$tax_rate->geo_zone_id = $request->input('geo_zone_id');
$tax_rate->tax_type = $request->input('tax_type');
$tax_rate->name = $request->input('name');
$tax_rate->code = $request->input('code');
$tax_rate->description = $request->input('description');
if(!empty($request->input('active'))){
$tax_rate->active =1;
} else {
$tax_rate->active =0;
}
$tax_rate->save();
if($tax_rate->tax_rate_id) {
TaxRateDetail::where('tax_rate_id', $tax_rate->tax_rate_id)->delete();
}
if($request->input('tax_rate_details')){
foreach ($request->input('tax_rate_details') as $key => $value) {
$tax_rate_detail = new TaxRateDetail();
$tax_rate_detail->tax_rate_id = $tax_rate->tax_rate_id;
$tax_rate_detail->priority = $value['priority'];
$tax_rate_detail->date_from = $value['date_from'];
$tax_rate_detail->date_to = $value['date_to'];
$tax_rate_detail->rate = $value['rate'];
$tax_rate_detail->type = $value['type'];
$tax_rate_detail->active = $value['active'];
//dd($tax_rate_detail);
$tax_rate_detail->save();
}
}
}
I want to save edit update with old(id). not create new. Please help thank you. I don't know where the code gone wrong.

How to get the value of a variable from the collection

public function returnsTrueIfEmailIsVerified(Request $request)
{
// Gets the email
$email = request("email"); //johndoe#example.com for example
// Determine if zero or one ;
$user = User::where('email','=',$email)->get(); // 0 or 1 ;
$userCount = User::where('email','=',$email)->count(); // 0 or 1 ;
$confirmedValue = $user->get('confirmed');
$response ;
if ( $user === 1 && $confirmedValue === true ) {
$response = 'OK';
}
elseif ($user === 1 && $confirmedValue === false) {
$response = 'Not Confirmed yet';
}
else {
$response = 'Not Registered yet';
}
return response()->json(200,$response);
}
with that code I would return a response that if a user isn't registered or is registered and that if he's registered but that he's not confirmed yet..
I want to return something out from that I'm not just familiar with laravel's way
There are so many error in your code, I've fixed it and this code will work. I think you need to learn more Laravel and PHP.
public function returnsTrueIfEmailIsVerified(Request $request)
{
$email = request("email");
$user = User::where('email', '=', $email);
$response = [
'message' => ''
];
if ($user->count() === 1) {
$confirmedValue = $user->first()->confirmed;
if ($confirmedValue) {
$response['message'] = 'OK';
} else {
$response['message'] = 'Not Confirmed yet';
}
} else {
$response['message'] = 'Not Registered yet';
}
return response()->json($response, 200);
}
you can't response string as a json, json is key value pair.
User::where('email', '=', $email) return Query Builder not 0 or 1, use count() method;
you can't retrieve value from multiple items you have to specific item like this $user->get()[0]['confirmed] or use Laravel special method $user->first()->confirmed

Laravel : API response with pagination parameter

I want to pass pagination parameters through POSTMAN and pass sort,order,limits in my model to get query with paginate.? how can i do this? Currently it return error.
Currently my route :
http://localhost:8000/api/allpost
My PostController function :
public function index(Request $request)
{
try {
$allPost = Post::allUserPost();
if($allPost !="" && count($allPost)>0) {
return [
'status_code' => 200,
'message' => "Post retrieved successfully",
'PostDetails' => $allPost,
];
} else {
return response()->json([
'message' => "Post data not found",
'status_code' => 403,
]);
}
} catch (\Exception $ex) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
}
And my POST model function :
public static function allUserPost(Request $request){
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
# code...
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
Currently it returns error
Type error: Too few arguments to function App\Post::allUserPost(), 0 passed in D:\xampp\htdocs\IDM\app\Api\V1\Controllers\Front\PostController.php on line 30 and exactly 1 expected
So how can i pass parameters in postmen and whats the solution for this error?
First change this line to $allPost = Post::allUserPost();
$allPost = Post::allUserPost($request);
and then change this code
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
To
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
and then you can pass these paramets in a query string like
http://localhost:8000/api/allpost?sort=somesort&order=asc&limit=10
Also chage this line
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
to
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
You are missing an argument when calling the allUserPost function inside the try block.
It should be
$allPost = Post::allUserPost($request);
and then you can retrieve the parameters from the $request variable.
Just change this line in your code
$allPost = Post::allUserPost($request);
And then in your function, you have to change your request type. And after that you have to do one more change only use paginate() method not with get() method.
public static function allUserPost(Request $request){
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
I hope this will help you.

Using with() and find() while limiting columns with find cancels relation data

I have the following code that displays different data depending on if you are the authenticated user looking at your own data or if you are looking at data from another user. The code works but in my opinion is very nasty.
public function showUserDetailed(Request $request, $username)
{
$key = strtolower($username).'-data-detailed';
if(Auth::user()->usenrame === $username) {
$key = $key .'-own';
}
if(Cache::has($key)) {
if($request->wantsJson()) {
return request()->json(Cache::get($key));
} else {
return view('user/detailed', ['user' => Cache::get($key)]);
}
} else {
if(Auth::user()->username === $username) {
$u = User::where('username', $username)->first();
$user = new \stdClass();
$user->username = $u->username;
$user->email = $u->email;
$user->address = $u->address;
$user->city = $u->city;
$user->state = $u->state;
$user->zip = $u->zip;
$user->phone = $u->phone;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
$user->location = $u->location;
} else {
$u = User::where('username', $username)->first(['username', 'city', 'state']);
$user = new \stdClass();
$user->username = $u->username;
$user->city = $u->city;
$user->state = $u->state;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
}
Cache::put($key, $user);
if($request->wantsJson()) {
return response()->json($user);
} else {
return view('user/detailed', ['user' => $user]);
}
}
}
I have tried to use something similar to the following in the model calls.
User::where('username', $username)->with('follows', 'ratings', 'location')->find(['username', 'city', 'state');
However when I specify the columns to get from the user table it negates the relation data so it comes back as empty arrays. Is there a different way I can do this which would be cleaner? I despise having to create a stdClass to be a data container in this situation and feel I may be missing something.
// this works
User::where('username', $username)->with('follows', 'ratings', 'location')->first();
// this also works
User::where('username', $username)->first(['username', 'city', 'state']);
// this does not
User::where('username', $username)->with('follows', 'ratings', 'location')->first(['username', 'city', 'state']);
When you specify columns and want to get the related models as well, you need to include id (or whatever foreign key you're using) in the selected columns.
The relationships execute another query like this:
SELECT 'stuff' FROM 'table' WHERE 'foreign_key' = ($parentsId)
So it needs to know the id of the parent (original model). Same logic applies to all relationships in a bit different forms.

Resources