Call to undefined method Illuminate\Database\Query\Builder::save()? - laravel-4

I'm getting this error after trying to save my model. This is the error I'm getting:
Call to undefined method Illuminate\Database\Query\Builder::save()
This is my code:
public function getActivate ($code)
{
$user = User::where('code','=',$code)->where('active','=',0);
if ($user->count())
{
$user->first();
//Update user to active state
$user->active = 1;
$user->code ='';
if($user->save())
{
return Redirect::route('home')
->with('global', 'Account Activated ! You can sign in ');
}
}
return Redirect::route('home')
->with('global', 'We could not activate your account. Try again later');
}
My version of Laravel is the stable one.

The problem is you are not getting the first instance of your user, and you are just calling the save() on the query itself.
Here is the updated code:
public function getActivate ($code)
{
$user = User::where('code','=',$code)->where('active','=',0)->first();
if ($user)
{
//Update user to active state
$user->active = 1;
$user->code ='';
if($user->save())
{
return Redirect::route('home')
->with('global', 'Account Activated ! You can sign in ');
}
}
return Redirect::route('home')
->with('global', 'We could not activate your account. Try again later');
}
Also, you may simplify your query build by replacing where($column, '=', $query) to
$user = User::whereCode($code)->whereActive(0)->first();

Related

Auth::user return null in laravel custom login

Users, roles, permissions have in my project.I have use custom login. I call Auth::user() return null.
How can I fix that?
public function check(LoginRequest $request)
{
$userInfo = User::where('email', '=', $request->email)->first();
if(!$userInfo){
return back()->with('message', 'We do not recognize your email address');
}
if($userInfo){
if(Hash::check($request->password, $userInfo->password)){
$request->session()->put('isUser', $userInfo->id);
$user = User::where('id', '=', session('isUser'))->first();
dd(Auth::user());
// dd($userInfo->roles);
// return redirect('home');
} else {
return back()->with('message', 'Incorrect password');
}
}
}
You need to pass the user instance to Auth::login() like this: Auth::user($user);;

ActivityLogger::performedOn() must be an instance of Illuminate\Database\Eloquent\Model, int given,

Why update does not return a Model instance , some can assist me.
Controller
public function cancel_bill_cash_store(Request $request){
$sales_cancel=Sales::where('bill_number',$request->bill_number)
->update(["cancel_bill" =>1,
"bill_status"=>$request->bill_status,
]);
if ($sales_cancel) {
activity('Sales')
->performedOn($sales_cancel)
->causedBy($user)
->log('Cancelled Bill by ' . $user->name . ' with IP '.request()->ip());
toastr()->success(' Bill- '.$request->bill_number.' Imeshakuwa Cancelled Vizuri!,
Device Zimerudi Store');
return redirect()->back();
}
else{
toastr()->error('Error: Kuna Kitu Kimekwenda Wrong !. Otherwise check Support.');
return redirect()->back();
}
}
I suggest a "divide and conquer" approach. Split your function into two and have one handle only the update and logging and the other handle the query:
public function cancel_bill(Sales $sales_cancel, $bill_status) {
$sales_cancel->cancel_bill = 1;
$sales_cancel->bill_status = $bill_status;
$result = $sales_cancel->save();
if ($result) {
activity('Sales')
->performedOn($sales_cancel)
->causedBy($user)
->log('Cancelled Bill by ' . $user->name . ' with IP '.request()->ip());
}
return $result;
}
public function cancel_bill_cash_store(Request $request) {
$sales_cancel=Sales::where('bill_number',$request->bill_number)
->first();
if ($sales_cancel && $this->cancel_bill($sales_cancel, $request->bill_status)) {
toastr()->success(' Bill- '.$request->bill_number.' Imeshakuwa Cancelled Vizuri!,
Device Zimerudi Store');
return redirect()->back();
} else {
toastr()->error('Error: Kuna Kitu Kimekwenda Wrong !. Otherwise check Support.');
return redirect()->back();
}
}
This gives each function a clear responsibility, one is responsible for updating the model and the other to create responses given the outcome.
Edit: If you have many rows you need to update you can do:
function cancel_bill_cash_store(Request $request) {
Sales::where('bill_number', $request->bill_number)
->get()
->each(function ($sales_cancel) use ($request) {
if ($sales_cancel && $this->cancel_bill($sales_cancel, $request->bill_status)) {
toastr()->success(
' Bill- ' . $request->bill_number . ' Imeshakuwa Cancelled Vizuri!,
Device Zimerudi Store');
} else {
toastr()->error('Error: Kuna Kitu Kimekwenda Wrong !. Otherwise check Support.');
}
});
return redirect()->back();
}
This will update each row and log the appropriate event.

Previous session can not destroy in laravel 5.7

I am creating login page & after logout my session value can not destroy. Any problem with code? I am using flush method,forget method to remove previous session value.
public function userLogin(Request $req)
{
$username=$req->input('username');
$password=$req->input('password');
$finduser = Users::where(['email'=>$username,'password'=>$password])
->orwhere(['mobile'=>$username,'password'=>$password])
->first();
Session::put('username', $finduser->name);
Session::put('userid', $finduser->id);
$session_id=Session::get('session_id');
if($username != $finduser->mobile and $username != $finduser->email)
{
Session::put('message','Email or mobile number does not exists');
return redirect::to('/login');
}
else if($password != $finduser->password)
{
Session::put('message','Your Password is incorrect');
return redirect::to('/login');
}
else if($finduser)
{
return redirect::to('/home');
}
}
public function logout(Request $req)
{
Session()->forget(['userid', 'username','session_id']);
Session()->flush();
//Session::flush();
return redirect('/login');
}
Try \Session()->flush(); instead of Session()->flush();

Google Client API setAccessToken() before isAccessTokenExpired() results in invalid credentials

I am working with the Google Client API in Laravel to allow my users to sync their calendars with Google. Everything works, but the issue I am running into is when their tokens expire they are getting an "Invalid Credentials" error, in order to fix it they have to log out and log back in which I am trying to avoid.
I don't understand why setAccessToken() is to be called before isAccessTokenExpired().
I need to check if the access token is expired before I set it but if I do it this way then isAccessTokenExpired() always returns true.
Any ideas would be helpful. Thanks!
Here is my code:
GoogeServiceController.php
class GoogleServiceController extends Controller
{
protected $client;
protected $service;
public function __construct()
{
$client = new Google_Client();
$client->setAuthConfig(Config::get('google_config.web'));
$client->setAccessType('offline');
$client->addScope(Google_Service_Calendar::CALENDAR);
$service = new Google_Service_Calendar($client);
$this->client = $client;
$this->service = $service;
}
public function oauth(Request $request)
{
if (App::environment('local')) {
$this->client->setRedirectUri('http://esm.development.com/oauth');
} else {
$this->client->setRedirectUri('https://essentialstudiomanager.com/oauth');
}
if (is_null($request->user()->refresh_token)) {
$this->client->setApprovalPrompt("force");
}
if (!$request->has('code')) {
$auth_url = $this->client->createAuthUrl();
$filtered_url = filter_var($auth_url, FILTER_SANITIZE_URL);
return redirect($filtered_url);
} else {
$this->client->authenticate($request->code);
if (is_null($request->user()->refresh_token)) {
$refresh_token = $this->client->getRefreshToken();
$user = $request->user();
$user->refresh_token = $refresh_token;
$user->save();
}
$request->session()->put('access_token', $this->client->getAccessToken());
$notification = ['message' => 'Your calendar is now synced with your Google Calendar.', 'alert-type' => 'success'];
return redirect()->route('home')->with($notification);
}
}
}
GoogleEventController.php
public function updateGoogleEvent($request, $event, $title, $description, $start, $end)
{
if ($request->session()->has('access_token')) {
$this->client->setAccessToken(session('access_token'));
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($request->user()->refresh_token);
$request->session()->put('access_token', $this->client->getAccessToken());
$this->client->setAccessToken(session('access_token'));
}
} else {
return redirect()->route('oauthCallBack');
}
$users_calendar = $this->service->calendars->get('primary');
$get_event = $this->service->events->get('primary', $event->google_event_id);
$get_event->setSummary($title);
$get_event->setDescription($description);
$start_date = new Google_Service_Calendar_EventDateTime();
$start_date->setDateTime($start);
$start_date->setTimeZone($users_calendar->timeZone);
$get_event->setStart($start_date);
$end_date = new Google_Service_Calendar_EventDateTime();
$end_date->setDateTime($end);
$end_date->setTimeZone($users_calendar->timeZone);
$get_event->setEnd($end_date);
$updatedEvent = $this->service->events->update('primary', $get_event->getId(), $get_event);
}

how to pass session variable into view using laravel4

I want to pass logged in id into my view page.i got the id in the function of user_login_submits.
Actually i want to get the id in one more function in the same controller.
how to get the session id in controller..
Normally session put its enough i did like that.
Here is my code anyone can check and tel me what need to change here
Controller
public function user_login_submits()
{
$inputs = Input::all();
$uname = Input::get('username');
$password = Input::get('password');
$logincheck=Userlogin::login_checks($uname,$password);
if($logincheck == 1)
{
$id=Session::get('customer_id');
return Redirect::to('businessprio/create_news?p=1');
}
else if($logincheck == 0)
{
//echo "fail";
return Redirect::to('businessprio/create');
}
}
Model
public static function login_checks($uname,$password)
{
$check = DB::table('customer_login')
->where('username','=',$uname)
->where('password','=',$password)->get();
if($check)
{
//Session::put(['customer_id'=>'value']);
Session::put('customer_id', $check[0]->customer_id);
Session::put('username', $check[0]->username);
return 1;
}
else
{
return 0;
}
}
I won't pass it to model, instead i would do it in controller itself,
public function user_login_submits()
{
$uname = Input::get('username');
$password = Input::get('password');
$check = DB::table('customer_login')
->where('username','=',$uname)
->where('password','=',$password)->count();
if($check==1)
{
$id=Session::get('customer_id');
return Redirect::to('businessprio/create_news?p=1');
}
else
{
return Redirect::to('businessprio/create');
}
}
Recommendation :
But i would strongly recommend you to do it by Auth::attempt i.e., to follow the clean one
public function user_login_submits()
{
if (Auth::attempt(['email' => $userEmail, 'password' => $userPassword])) {
return Redirect::to('businessprio/create_news?p=1');
}
else
{
return Redirect::to('businessprio/create');
}
}
If you do so, then you can access the Default checking for authenticated user
Auth::check()
Get the Logged in user details by
Auth::user()->id
Auth::user()->username
Note : To use default Auth::attempt you should use the User Model too.

Resources