When i work on locally upload image on folder works perfect but when i try to upload image on amazon web server file not uploaded and back with same page.Is there any problem with my code ?
Here is my controller function to save data :
// CountryController
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules());
//$request->validate(Country::rules());
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
And my model code look like:
//country model
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Country extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'short_name',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$country = false;
DB::transaction(function () use ($request, &$country, $id) {
$country = $id ? Country::findOrFail($id) : new Country();
$country->fill($request->all());
try {
$country->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $country;
} catch (\Exception $ex) {
throw $ex;
}
} }
What's the problem i didn't find anything.
Related
I have done my coding but the laravel audit seems not catch the data for update.
The data i try to update is on the column of value, but on the database the value are not be catch on audit table for auditing the update changes .
below is the coding for update the data.
academicsetting.php:
class AcademicSetting extends Model implements Auditable
{
use SoftDeletes, ActiveScope;
use \OwenIt\Auditing\Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
protected $fillable = [
'id',
'type',
'field',
'name',
'value',
'description',
'is_active',
'created_by',
'created_at',
'updated_by',
'updated_at',
'deleted_by',
'deleted_at',
];
protected $casts = [
'value' => 'json',
];
public function transformAudit(array $data): array
{
dump($data);exit();
if ($data['event'] == 'created') {
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
if ($data['event'] == 'deleted') {
$data['old_values']['deleted_by'] = Staff::where('id', $this->getOriginal('deleted_by'))->value('name');
$data['new_values']['deleted_by'] = Staff::where('id', $this->getAttribute('deleted_by'))->value('name');
}
if ($data['event'] == 'updated') {
$data['old_values']['updated_by'] = Staff::where('id', $this->getOriginal('updated_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
return $data;
}
}
academicgeneralcontroller.php:
public function update(Request $request, $id)
{
/** implode multi dropdown value */
$request['final_attendance_reset_mark'] = $request->input('final_attendance_reset_mark');
/** end */
$this->general->update($request->except('_token', 'academicsetting-table_length', '_method'), $id);
Session::flash('alert-success', msg('msg_success_update'));
return redirect()->route('academic_general.index');
}
generalrepository.php:
class GeneralRepository extends Repository
{
/**
* Specify Model class name
*
* #return mixed
*/
public function model()
{
return AcademicSetting::class;
}
public function update(array $data, $id, $attribute = 'id')
{
// dump($data);exit();
foreach ($data as $key => $value) {
if ($key == 'final_attendance_reset_mark') {
$array = [];
if (!empty($value)) {
foreach ($value as $key_value => $value) {
$array[(int) $key_value] = (int) $value;
}
}
$json = json_encode($array, JSON_FORCE_OBJECT);
// dump($json);
$update_value = [
'value' => $json,
];
} else {
$update_value = ['value' => $value];
}
dump($update_value);exit();
$general = AcademicSetting::where('field', $key)->update($update_value);
}
}
}
Not sure if this will help but,
i see you have the following in the transform method:
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
in the documentation i see the following:
$data['old_values']['role_name'] = Role::find($this->getOriginal('role_id'))->name;
the above is to record the audit by transforming the role_id to the role_name, enabling you to capture the role_name as well.
https://laravel-auditing.herokuapp.com/docs/4.1/audit-transformation
I am using Socialite for Google Authentication, i have an middleware for check that if user exist in my local database by their google_id, it can redirect to /home page otherwise it will redirect back to Google Authentication page, while doing this i am facing issue in middle and the error is:
Client error: POST https://www.googleapis.com/oauth2/v4/token resulted in a 400 Bad Request response: { "error": "invalid_request", "error_description": "Missing required parameter: code" }
Middleware
<?php
namespace App\Http\Middleware;
//use Socialite;
use App\GmailAccount;
use Closure;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
class GoogleAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Socialite::driver('google')->stateless()->user();
$finduser = GmailAccount::where('google_id', $user->id)->first();
if($finduser){
return $next($request);
}
else{
return route('/logingoogle');
}
}
}
Routes
Route::group(['middleware' => 'App\Http\Middleware\GoogleAuth'], function()
{
Route::get('/home', 'HomeController#index')->name('home');
});
Route::get('/logingoogle', 'GoogleController#google_login');
Route::get('auth/google', 'GoogleController#redirectToGoogle');
Route::get('auth/google/callback', 'GoogleController#handleGoogleCallback');
HomeController
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('googleauth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user_id=Auth::user()->id;
$user_messages=DB::table('user_message')
->join('messages', 'user_message.message_id', '=', 'messages.id')
->where([
'user_message.user_id' => $user_id,
'user_message.placeholder' => 'inbox'
])
->select('messages.*', 'user_message.message_id', 'user_message.user_id','user_message.is_read')
->orderBy('messages.id', 'DESC')
->paginate(10);
return view('website_pages.home',compact('user_messages'));
}
}
GoogleController
class GoogleController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function google_login(){
return view('website_pages.login_google');
}
public function redirectToGoogle()
{
return Socialite::driver('google')->stateless()->redirect();
}
/**
* Create a new controller instance.
*
* #return void
*/
public function handleGoogleCallback()
{
$login_user_id = Auth::user()->id;
try {
$user = Socialite::driver('google')->stateless()->user();
$finduser = GmailAccount::where('google_id', $user->id)->first();
if($finduser){
return redirect('/home');
}
else{
$newUser = DB::table('gmail_accounts')->updateOrInsert(
[
'email' => $user->email,
],
[
'user_id' => $login_user_id,
'email' => $user->email,
'google_id'=> $user->id,
'remember_token'=> $user->token
]
);
if ($newUser){
return redirect('/home');
}
else{
return redirect()->back();
}
Auth::login($newUser, true);
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
GmailAccount Model
class GmailAccount extends Model
{
protected $table = 'gmail_accounts';
protected $fillable = [
'email', 'password', 'google_id', 'user_id', 'remember_token'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
Can you try this?
if($finduser) {
auth()->login($finduser), true);
}
else {
return redirect('/logingoogle');
}
And include these:
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
Follow this which is a working example:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use App\User;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if ($existingUser) {
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->lastlogin_at = \Carbon\Carbon::now();
$newUser->save();
auth()->login($newUser, true);
}
session(['user_name' => $user->name]);
session(['user_email' => $user->email]);
session(['user_avatar' => $user->avatar]);
return redirect()->to('/home');
}
}
Route::get('/redirect', 'Auth\LoginController#redirectToProvider');
Route::get('/callback', 'Auth\LoginController#handleProviderCallback');
I'm trying to save new user with Ajax request in Laravel and i'm getting the following error,
Object of class App\User could not be converted to int
I must add the the user is saved, so i'm not sure from where this error comes.
Here is the UserController:
public function save_user(Request $request)
{
try {
if (request()->ajax()) {
$lastUserId = User::where('user_id', '>', 0)->orderBy('user_id', 'desc')->get('user_id')->first()->toArray();
$user = new User;
$data = Input::all();
$user->user_id = intval($lastUserId['user_id'] + 1);
$user->user_type = $data['user_type'];
$user->email = $data['email'];
$user->password = 'e10adc3949ba59abbe56e057f20f883e';
$user->first_name = $data['first_name'];
$user->last_name = $data['last_name'];
$user->save();
if ($user > 0) {
return response()->json('Success');
}
return response()->json(['status' => 200, 'message' => 'save success']);
}
} catch (\Exception $e) {
echo $e->getMessage();
}
Here is the Ajax request:
$('#saveUser').on('click', function (e) {
e.preventDefault();
var $inputs = $('#new-user-form :input');
var values = {};
$inputs.each(function () {
if (this.name != '_token' && this.name.length > 0) {
values[this.name] = $(this).val();
}
});
$.ajax({
url: '/api/save_user',
type: "post",
data: values,
dataType: 'JSON',
success: function (data) {
/// location.reload();
}
});
})
Here is the User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Detail;
class User extends Authenticatable
{
public function users(){
return $this->hasMany('\App\User'); //Product Model Name
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I've tried to convert all the input values to their type - like in the DB but it didn't worked
In your condition, you are trying to see if a collection of user is > 0, and because of that, you're getting the error above, since Laravel is trying to parse the collection of user to int datatype, to make it countable. Refactor your condition to this:
if (count($user) > 0) {
return response()->json('Success');
}
or another way:
if ($user) {
return response()->json('Success');
}
Try to change this in your controller
if ($user > 0) {
return response()->json('Success');
}
To this
if ($user) {
return response()->json('Success');
}
Facing a problem on submit form data.
When I fill up all form data then it is inserted into the database. But when I fill only mandatory field data and leave other data as blank it is not working and it redirect to the same form.
On removing validation also not working.
My controller function code:
public function save(Request $request) {
try {
$validator = Validator::make($request->all(), Activity::rules());
$activity = Activity::saveOrUpdate($request);
if($activity !== false) {
return redirect()->route('lists-activity')->with('success', trans('activity data added successfully.!!'));
} else {
return back()->with('error', "Unable to save activity data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save activity data.!!")->withInput()->withErrors($validator);
}
}
My model code :
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Activity extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'category_id',
'title',
'description',
'country_id',
'city_id',
'latitude',
'longitude',
'addressOne',
'addressTwo',
'hours_recomended',
'hours_fixed',
'time_fixed',
'start_time',
'end_time',
'file_type',
'flag_image'
];
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'category_id' => 'required',
'title' => 'required|string|max:255',
'country_id' => 'required',
'city_id' => 'required',
'hours_fixed' => 'required',
'start_time' => 'required',
'end_time' => 'required'
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$activity = false;
DB::transaction(function () use ($request, &$activity, $id) {
$activity = $id ? Activity::findOrFail($id) : new Activity();
$activity->fill($request->all());
try {
$activity->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $activity;
} catch (\Exception $ex) {
throw $ex;
}
} }
Form view :
Don't know what I am doing wrong?
Looks like validation works and redirects back as it supposes to do.
Put {{ dump($errors->all()) }} to the view and you'll see errors in the form after submitting the form.
Also, use the updateOrCreate() which does exactly what you're trying to do and will help you to avoid errors:
public static function saveOrUpdate(Request $request) {
return $this->updateOrCreate(['id' => $request->id], $request->all());
}
We are working on two laravel projects one for front end laravel and for backend api. I followed tutorials on connecting this two projects but make use of guzzlehttp. However I am getting undefined index password. I already dd the user['data'] in getUsers method and gettign the correct password. Can any one help me on this.
ApiUserProvider
<?php
namespace App\Auth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class ApiUserProvider implements UserProvider
{
public function retrieveByCredentials(array $credentials)
{
$user = $this->getUserByUsername($credentials['username']);
return $this->getApiUser($user);
}
public function retrieveById($identifier)
{
$user = $this->getUserById($identifier);
return $this->getApiUser($user);
}
public function validateCredentials(UserContract $user, array $credentials)
{
return $user->getAuthPassword() == bcrypt($credentials['password']);
}
protected function getApiUser($user)
{
if ($user !== null) {
return new ApiUser($user);
}
}
protected function getUsers()
{
$client = new Client(['base_uri' => 'http://127.0.0.1:80/api.kourse/public/api/v1/']);
$response1 = $client->request('POST', 'oauth/access_token', [
'form_params' => [
'client_id' => 'id1',
'client_secret' => 'secret1',
'grant_type' => 'password',
'username' => 'email#yahoo',
'password' => 'password'
]
]);
$location = json_decode($response1->getBody(), true);
$token = $location['access_token'];
// Send a request to https://foo.com/api/test
$response2 = $client->request('GET', 'users/self', [
'headers' => [
'Authorization' => 'Bearer '. $token
]
]);
$user = json_decode($response2->getBody(), true);
return $user['data'];
}
protected function getUserById($id)
{
$user = [];
if($this->getUsers()['email'] == $id){
$user['id'] = $id;
}
dd($user);
return $user ?: null;
}
protected function getUserByUsername($username)
{
$user = [];
if($this->getUsers()['email'] == $username){
$user['email'] = $username;
}
return $user ?: null;
}
// The methods below need to be defined because of the Authenticatable contract
// but need no implementation for 'Auth::attempt' to work and can be implemented
// if you need their functionality
public function retrieveByToken($identifier, $token) { }
public function updateRememberToken(UserContract $user, $token) { }
}
ApiUser
namespace App\Auth;
use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class ApiUser extends GenericUser implements UserContract
{
public function getAuthIdentifier()
{
return $this->attributes['id'];
}
}
UserController
public function login(Request $request)
{
$email = $request->email;
$password = bcrypt($request->password);
if (Auth::attempt(['username' => $email, 'password' => $password])) {
return "hello";
}
}
error
AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* #param \Illuminate\Contracts\Auth\Access\Gate $gate
* #return void
*/
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
Auth::provider('api', function($app, array $config) {
return new ApiUserProvider($config['model']);
});
}
}
My best guess would be to open then User model and if you have:
protected $hidden = [
'password',
'remember_token',
];
to make it an empty array, like this protected $hidden = [];. I guess this might work because when you make new ApiUser return new ApiUser($user); it's converting the User object to array and it removes the password attribute because of the $hidden property.