Laravel - Call to undefined method App\\User::getAvatarUrlAttribute() - laravel

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?

You do not have the column avatar on your users table.

Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}

I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Related

How can I update image in Laravel

How to update image in this code?
this is the Web.php file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\auth\DashboardController;
use App\Http\Controllers\auth\ServicesController;
use App\Http\Controllers\Auth\TournamentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
//Admin Middleware
Route::prefix('admin')->middleware(['auth', 'isAdmin'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'dashboard']);
Route::get('/alltournaments', [TournamentController::class, 'createview']);
Route::get('/create', [TournamentController::class, 'create']);
Route::post('/save-tournament', [TournamentController::class, 'saveTournament']);
Route::get('/edit-tournament/{id}', [TournamentController::class, 'editTournament']);
Route::post('/update-tournament', [TournamentController::class, 'updateTournament']);
Route::get('delete-tournament/{id}', [TournamentController::class, 'deleteTournament']);
Route::get('/manage', [TournamentController::class, 'manage']);
});
//User Middleware
Route::middleware(['auth', 'isUser'])->group(function () {
});
//Public Routes
Route::get('/', [TournamentController::class, 'index']);
Route::get('/tournament/{id}', [TournamentController::class, 'singleTournament']);
And this is controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use App\Models\Tournament;
use Illuminate\Support\Facades\File;
class TournamentController extends Controller
{
public function index(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('site.home', compact('data'));
}
public function createview(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('auth.createmain',compact('data'));
}
//manage view
public function manage(){
$data = Tournament::latest()->get();
return view('auth.manage', compact('data'));
}
//create view
public function create(){
return view('auth.create');
}
//Create
public function saveTournament(Request $request ){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
$tournament = new Tournament();
$tournament->title = $tournament_name;
$tournament->check_in_period = $check_in_period;
$tournament->entry_fee = $fee;
$tournament->formate = $formate;
$tournament->overview = $overview;
$tournament->teamsize = $teamsize;
$tournament->prize_pool = $prize_pool;
if($request->hasfile('thumnial'))
{
$file=$request->file('thumnial');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/thumnail/',$filename);
$tournament->thumnail=$filename;
}
if($request->hasfile('banner'))
{
$file=$request->file('banner');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/banner/',$filename);
$tournament->banner=$filename;
}
$tournament->save();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Added');
}
//create END
public function editTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
return view('auth.edit', compact('data'));
}
public function updateTournament(Request $request){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$id =$request->id;
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
Tournament::where('id' , '=', $id)->update([
'title'=> $tournament_name,
'teamsize'=>$teamsize,
'check_in_period'=> $check_in_period,
'formate'=>$formate,
'entry_fee'=>$fee,
'prize_pool'=>$prize_pool,
'overview'=>$overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}
//Delete
public function deleteTournament($id){
Tournament::where('id' , '=', $id)->delete();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Deleted');
}
//User View
public function singleTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
if($data->teamsize == 1){
$data->teamsize = "Solo";
}elseif($data->teamsize == 2){
$data->teamsize = "Duo";
}elseif($data->teamsize == 4){
$data->teamsize = "Squad";
}
return view('site.tournament',compact('data'));
}
}
I need to update image
You can update the image by only inserting this small code:
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
}
Also, below i update your function:
public function updateTournament(Request $request)
{
$request->validate([
'tournament_name' => 'required',
'teamsize' => 'required',
'check_in_period' => 'required',
'formate' => 'required',
'fee' => 'required',
'prize_pool' => 'required',
'overview' => 'required',
]);
$id = $request->id;
$tournament_name = $request->tournament_name;
$teamsize = $request->teamsize;
$check_in_period = $request->check_in_period;
$formate = $request->formate;
$fee = $request->fee;
$prize_pool = $request->prize_pool;
$overview = $request->overview;
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
Tournament::where('id', $id)->update(['banner' => $banner]);
}
Tournament::where('id', $id)->update([
'title' => $tournament_name,
'teamsize' => $teamsize,
'check_in_period' => $check_in_period,
'formate' => $formate,
'entry_fee' => $fee,
'prize_pool' => $prize_pool,
'overview' => $overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}

How to Reset Password without entering email field

I'm creating a reset password with the help of the internet I'm able to make it function, but it needs to input an email address in the email field. I want to hide the email field and only the password field need to input. How can i do that?
My ForgotPasswordController
class ForgotPasswordController extends Controller
{
public function getEmail()
{
return view('auth.passwords.email');
}
public function postEmail(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
]);
$token = Str::random(60);
DB::table('password_resets')->insert(
['email' => $request->email, 'token' => $token, 'created_at' => Carbon::now()]
);
Mail::send('auth.verify',['token' => $token], function($message) use ($request) {
$message->from('noreply#taskproph.com');
$message->to($request->email);
$message->subject('Reset Password Notification');
});
Toastr::success('We have e-mailed your password reset link! :)','Success');
return back();
}
}
My ResetPasswordController
class ResetPasswordController extends Controller
{
public function getPassword($token)
{
return view('auth.passwords.reset', ['token' => $token]);
}
public function updatePassword(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
]);
$updatePassword = DB::table('password_resets')->where(['email' => $request->email, 'token' => $request->token])->first();
if(!$updatePassword)
{
Toastr::error('Invalid token! :)','Error');
return back();
}else{
$user = User::where('email', $request->email)->update(['password' => Hash::make($request->password)]);
DB::table('password_resets')->where(['email' => $request->email ])-> delete();
Toastr::success('Your Password has been changed! :)','Success');
return redirect('/login');
}
}
}
In your getPassword method you may get email. Then you can use it email to updatePassword method by passing on it hiddenly.
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Password;
public function getPassword(Request $request, $token)
{
$email = $request->input('email');
$user = User::where('email', $email)->firstOrFail();
if(!Password::tokenExists($user, $token)) {
Toastr::error('Invalid token!','Error');
return redirect()->route('password.request');
}
return view('auth.passwords.reset', ['token' => $token, 'email' => $email ]);
}
public function updatePassword(ResetPasswordRequest $request)
{
$credentials = $request->validated(); // email, token, password, password_confirmation
$status = Password::reset($credentials, function($user) use($request) {
$user->forceFill([
'password' => bcrypt($request->password)
])->save();
event(new PasswordReset($user));
});
if ($status != Password::PASSWORD_RESET) {
Toastr::error(__($status), 'Error');
return back();
}
$request->session()->flash('statusForgotPassword', __($status));
Toastr::success('Your Password has been changed!','Success');
return redirect('/login');
}
auth.passwords.reset
<input type="hidden" name="email" value="{{ $email }}">

Laravel - Maatwebsite Excel import stored in storage only but not in DB

I am importing Excel File using Laravel-8 endpoints and Maatwebsite-3.1 package.
The way I did it is that, the Uploaded Excel file will first get to the storage (storage/file_imports/student_imports). Then Laravel pickes it up from there, stores it into the DB table through StudentImport using Maatwebsites.
StudentImport:
<?php
namespace App\Imports;
use App\Models\User;
use App\Models\Student;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Validators\Failure;
use Throwable;
class StudentImport implements
ToModel,
WithValidation,
WithHeadingRow,
SkipsOnError,
SkipsOnFailure,
WithBatchInserts
{
protected $companyId;
public function __construct()
{
$this->companyId = Auth::user()->company_id;
}
use Importable, SkipsErrors, SkipsFailures;
public function model(array $row)
{
$student_data = [
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'gender' => $row[4],
'nationality_id' => $this->getNationality() ?? '',
'school_id' => Auth::user()->school_id,
];
$student = Student::create($student_data);
if (User::where('email', '=', $student->email)->exists()) {
$user = User::update([
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'complete_profile' => 1,
'active' => 1,
'user_type' => 'Driver',
'company_id' => Auth::user()->company_id,
'updated_at' => date("Y-m-d H:i:s"),
'updated_by' => Auth::user()->id,
]);
}else{
$user = User::create([
'email' => $student->email,
'username' => strtok($row[3], '#'),
'password' => bcrypt("123456"),
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'activation_token' => str_random(10),
]);
}
}
public function headingRow(): int
{
return 1;
}
public function getRowCount(): int
{
return $this->rows;
}
public function customValidationAttributes()
{
return [
'0' => 'First Name',
'1' => 'Other Name',
'2' => 'Last Name',
'3' => 'Email',
'4' => 'Gender',
];
}
public function rules(): array
{
return [
'*.0' => [
'required',
'string',
'max:50'
],
'*.1' => [
'nullable',
'string',
'max:50'
],
'*.2' => [
'required',
'string',
'max:50'
],
'*.3' => [
'required',
'email',
'max:100',
Rule::unique('studentss')->where(function ($query) {
return $query->where('school_id', Auth::user()->school_id);
})
],
'*.4' => [
'required',
'string',
'max:20'
],
];
}
public function batchSize(): int
{
return 1000;
}
public function chunkSize(): int
{
return 1000;
}
public function onFailure(Failure ...$failures)
{
// Handle the failures how you'd like.
}
public function customValidationMessages()
{
return [
'1.in' => 'Custom message for :attribute.',
'nim.unique' => 'Custom message',
];
}
}
Controller:
public function importStudent(Request $request)
{
try {
$user = Auth::user()->id;
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xlsx|max:10000',
]);
if($validator->fails()) {
return $this->error($validator->errors(), 401);
} else {
$check = User::where('id', $user)->pluck('id');
if($check[0] !== null || $check[0] !== undefined) {
$file = $request->file('document');
$file->move(public_path('storage/file_imports/student_imports'), $file->getClientOriginalName());
Excel::import(new StudentImport, public_path('storage/file_imports/student_imports/' . $file->getClientOriginalName() ));
return $this->success('Students Successfully Imported.', [
'file' => $file
]);
} else {
return $this->error('Not allowed', 401);
}
}
} catch(\Exception $e) {
return $this->error($e->getMessage());
}
}
As I stated earlier it will first store the Excel file into:
storage/file_imports/student_imports
Then pick it from there and store in the DB.
This code is in the controller above.
The file is store in the
public/storage/file_imports/student_imports
as expected, but nothing is found in the DB. Yes it displays Success with no error.
What could be the problem and how do I resolve it?
Thanks
model method in your StudentImport class must return new instance of Eloquent model.
You shouldn't make create or update method call through your model in here.
Maatwebsite-Excel manage your insert process with own manager. Check source code.
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L74
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L92
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L45
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L64

Sending email from 2 different mail classes and laravel throws error

I am sending two different emails. One from VerifyMail and other from ForgetEmail but laravel throws error that VerifyMail does not exits. It was working just fine when i had not added the ForgetMail class.
This is my code where i am using VerifyMail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\VerifyUser;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Carbon;
use App\Mail\VerifyMail;
class UserRegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest:user');
}
public function showRegisterForm() {
return view('user.registerForm');
}
public function register(Request $request) {
$userValidated = $this->validate($request, [
'name' => 'required|string',
'email' => 'required|string|unique:users',
'password' => 'required|string|min:6|confirmed'
]);
$register = [
'name' => $userValidated['name'],
'email' => $userValidated['email'],
'password' => Hash::make($userValidated['password']),
];
$user =User::create($register);
VerifyUser::create([
'token' => str::random(60),
'user_id' => $user->id,
]);
Mail::to($user->email)->send(new VerifyMail($user));
return redirect('user/login')->with('email', 'An email was sent to you for verification');
}
public function verifyEmail($token, $date) {
$dates = date(strtotime($date));
if(time() - $dates > 60 * 60) {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
$verifiedUser = VerifyUser::where('token', $token)->first();
if(isset($verifiedUser)) {
$user = $verifiedUser->user;
if($user->email_verified_at == '') {
$user->email_verified_at = carbon::now();
$user->save();
return redirect('/user/login')->with('success', 'Your email was successfully verified');
} else {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
}
}
}
This is the code where i am using ForgetEmail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// use Symfony\Component\HttpFoundation\Session\Session;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use App\ForgetPassword;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ForgetEmail;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserLoginController extends Controller
{
protected $guard;
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:user')->except('logout');
$this->guard = Auth::guard('user');
}
public function showLoginForm()
{
return view('user.login');
}
public function forgetPasswordForm() {
return view('user.forget');
}
public function passwordResetForm($id) {
$user = User::where('id', $id)->first();
return view('user.resetForm', ['id' => $id]);
}
public function userLogin(Request $request) {
$validated = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if(Auth::guard('user')->attempt(['email' => $validated['email'], 'password' => $validated['password']], $request->remember)) {
$user = Auth::guard('user')->user();
if($user->email_verified_at != null) {
return redirect()->route('user.dashboard');
} else {
$this->logout($msg = 1);
}
}
return redirect()->back();
}
public function forgetPassword(Request $request) {
$email = $this->validate($request, [
'email' => 'required|email|exists:users',
]);
$forgetPass = User::where('email', $email['email'])->first();
$forgetArray = array(
'user_id' => $forgetPass->id,
'token' => str::random(60),
);
$forgetPassword = ForgetPassword::create($forgetArray);
Mail::to($email['email'])->send(new ForgetEmail($forgetPassword->user));
return redirect('user/forgetPassword')->with('email', 'We have sent you an email to reset your password');
}
public function passwordReset($token, $date) {
$checkTime = strtotime($date);
if(time() - $checkTime > 20 * 60) {
return redirect('user/login/')->with('passes', 'Looks like the link has expired');
}
$passReset = ForgetPassword::where('token', $token)->first();
if(isset($passReset)) {
$user = $passReset->user;
if($user->password) {
return redirect('/user/passwordReset'. '/'. $user->id);
}
}
}
public function passwordUpdate(Request $request, $id) {
$validatePass = $this->validate($request, [
'password' => 'required|string|min:6|confirmed',
]);
$pass = User::where('id', $id)->first();
$pass->password = Hash::make($validatePass['password']);
$pass->save();
return redirect('/user/login')->with('reset', 'Your password has been reset');
}
public function logout($msg = 0) {
$cookieName = $this->guard->getRecallerName();
$cookie = Cookie::forget($cookieName);
Auth::logout();
Session::flush();
if($msg == 0) {
return redirect()->route('user.login')->withCookie($cookie);
} else {
return redirect()->route('user.login')->withCookie($cookie)->with('verify', 'Your email is not verified');
}
}
}
All of my code was working fine before when i had not added that ForgetEmail class in Mail. I don't know what's the problem here. Will be glad if you can find it for me.

Laravel passport create token doesnt work on plesk server

I use passport in my laravel project to authenticate users by api. API work correctly on my local host. But after i deploy it on Plesk server token doesnt create. Always show Server Error.
public function login(Request $request) {
$validator = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
return response()->json(["validation errors" => $validator->errors()]);
}
$email = $request->email;
$password = $request->password;
error_log($password);
$user = DB::table("users")->where([["email", "=", $email]])->first();
if(is_null($user)) {
return response()->json(["success" => false, "message" => "User doesn't exist"]);
}
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('token')->accessToken;
$success['success'] = true;
$success['user'] = $user;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token;
return response()->json(['success' => $success ], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
$token = $user->createToken('token')->accessToken;
This line throw error
Problem was in my AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'Medicare\Model' => 'Medicare\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
After i commented 'Medicare\Model' => 'Medicare\Policies\ModelPolicy' everything works fine.

Resources