/** * Convert an authentication exception into an unauthenticated response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response */ protected function unauthenticated($request, AuthenticationException $exception) { if ($request->expectsJson()) { return response()->json(['error' => 'Unauthenticated.'], 401); } return redirect()->guest('login'); }
/** * For autocompleting. * Select rows from both foods and recipes table. * * @VP: I feel like I should transform the foods and recipes here, * to be consistent, but then there would be so much stuff I don't need. * (For example, I only need the name and id for the recipes.) * * So I did use transformers, but it's a bit of a mess, * and I suppose there's a better way to write this code, * since I'm adding the * data attribute at the end just so it's consistent with * my other autocomplete responses. * @param Request $request * @return mixed */ public function index(Request $request) { $typing = '%' . $request->get('typing') . '%'; $foods = $this->foods($typing); //I didn't transform this because I only need the id and name $recipes = $this->recipes($typing)->toArray(); $foods = $this->transform($this->createCollection($foods, new FoodTransformer()), ['units'])['data']; //Specify whether the menu item is a food or recipe foreach ($foods as $index => $food) { $foods[$index]['type'] = 'food'; } $menu = $foods; foreach ($recipes as $recipe) { $recipe['type'] = 'recipe'; $menu[] = $recipe; } //Sort by name and change the array indexes so they are ordered correctly, too //(Having the indexes ordered correctly makes it easier to test the ordering is correct) usort($menu, function ($a, $b) { return strcmp($a["name"], $b["name"]); }); //So that for populating the autocomplete, there is a //data attribute like the food and exercise autocomplete responses $response = ['data' => $menu]; return response($response, Response::HTTP_OK); }
/** * @param string $model The model to list. * @return mixed */ public function index(Request $request, $model) { if (!Auth::check()) { return response("Unauthorised", 401); } $user = Auth::user(); if ($user->cannot('administrate')) { return response("Unauthorised", 401); } $class = $this->getModel($model); if (is_null($class)) { return response("No items found for this model {$model}", 404); } $pagination_enabled = config('crudapi.pagination.enabled'); $perPage = config('crudapi.pagination.perPage'); if ($pagination_enabled) { $items = $class->paginate($perPage); } else { $items = $class->all(); } $fields = $class->getFillable(); $data = $this->buildData(); $data['items'] = $items; $data['model'] = $model; $data['fields'] = $fields; $data['uiframework'] = config('crudapi.framework', 'bs3'); $data['timestamps'] = config('crudapi.admin.showTimestamps', false); $data['show_ids'] = config('crudapi.admin.showIds', false); return view('crudapi::admin.index', $data); }
public function download($id) { $file = File::findOrFail($id); $pathToFile = 'get_link_to_download/' . md5($file->name . time()); FileHelpers::copy(storage_path('app') . '/' . $file->local_name, $pathToFile); return response()->download($pathToFile, $file->name, ['Content-Type'])->deleteFileAfterSend(true); }
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { /*if(NotFoundHttpException instanceof $e){*/ return response()->view('welcome'); /*}*/ return parent::render($request, $e); }
public function destroy($id) { $todo = Todo::findOrFail($id); $this->authorize('touch', $todo); $todo->delete(); return response($todo, 200); }
public function updateArticle(Request $request, $id) { $article->title = $request->input('title'); $article->content = $request->input('content'); $article->save(); return response()->json($article); }
public function saveAdminUser(SaveAdminUserPostRequest $request) { $user = User::create(['username' => $request->input('username'), 'displayname' => $request->input('displayname'), 'email' => $request->input('email'), 'password' => bcrypt($request->input('password')), 'user_role_id' => $request->input('role_id')]); $user->is_active = true; $user->save(); return response()->json(['status' => 'success', 'message' => 'New Admin User Created.']); }
public function postActualizarcosto(Request $req) { $detalle = DetalleArticulo::findOrFail($req->get('id')); $detalle->fill($req->only('costo_compra')); $detalle->save(); return response()->json(); }
public function render($request, Exception $e) { if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return response(view('errors.missing'), 404); } return parent::render($request, $e); }
public function store(Request $request) { //Seteo la zona horaria date_default_timezone_set('America/Argentina/Buenos_Aires'); if ($request->ajax()) { $persona_registrada = DB::select('select * from personas WHERE documento like "' . $request->username . '"'); $personas = DB::select('select * FROM personas p1 INNER JOIN evento_persona t2 ON p1.id = t2.persona_id WHERE p1.documento like "' . $request->username . '"' . ' and t2.evento_id = ' . $request->evento_id); if (!empty($personas) && is_array($personas)) { //verifico que el array tenga datos if ($this->validarAsistencias($personas, $request->evento_id)) { //valido cantidad maxima de asistencias if ($this->validarUltimoIngreso($personas, $request->evento_id)) { //valido tolerancia $this->insertAsistencia($personas); //inserto asistencias } } array_push($personas, ["valor" => Config::get('constant.MENSAJE')]); return response()->json($personas); } else { if (empty($persona_registrada)) { array_push($personas, ["valor" => Config::get('constant.MENSAJE_ERROR')]); } else { array_push($personas, ["valor" => Config::get('constant.MENSAJE_NO_PERTENECE_EVENTO')]); } return response()->json($personas); } } }
/** * @return mixed */ public function create() { $users = User::with('employee')->get()->reject(function ($user) { return $user->id === auth()->user()->id; }); return response()->view('messages.create', with(compact('users'))); }
/** * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\JsonResponse */ public function resolveIdsToNames(Request $request) { $ids = array_unique(explode(',', $request->ids)); // Init the initial return array $response = []; // Populate any entries from the cache foreach ($ids as $id) { if (Cache::has($this->prefix . $id)) { $response[$id] = Cache::get($this->prefix . $id); unset($ids[$id]); } } // Call the EVE API for any outstanding ids that need // resolution if (!empty($ids)) { $pheal = app()->make('Seat\\Eveapi\\Helpers\\PhealSetup')->getPheal(); foreach (array_chunk($ids, 30) as $id_chunk) { $names = $pheal->eveScope->CharacterName(['ids' => implode(',', $id_chunk)]); foreach ($names->characters as $result) { Cache::forever($this->prefix . $result->characterID, $result->name); $response[$result->characterID] = $result->name; } } } return response()->json($response); }
public function optimize($hash) { $folder = $this->getImagePath($hash); //Check if image exists. If not, throw exception. if (is_null($folder)) { throw new Exception('Image does not exists.'); } //Check if any etag is set. if (!empty(request()->instance()->getETags())) { return response(null)->setNotModified(); } $newHeight = $this->getDimensionValue('h'); $newWidth = $this->getDimensionValue('w'); $this->image->readImage(sprintf('%s/%s', $folder, $hash)); if (filter_var($newWidth, FILTER_VALIDATE_INT) && filter_var($newHeight, FILTER_VALIDATE_INT)) { $this->crop($newWidth, $newHeight); } else { if (filter_var($newWidth, FILTER_VALIDATE_INT) && $newHeight === 'auto') { $this->resize($newWidth, 0); } else { if (filter_var($newHeight, FILTER_VALIDATE_INT) && $newWidth === 'auto') { $this->resize(0, $newHeight); } } } return response($this->image)->header('Pragma', 'Public')->header('Content-Type', $this->image->getImageMimeType())->setEtag(md5(sprintf('%s-%s', $hash, $_SERVER['QUERY_STRING'])))->setPublic(); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if ($this->auth->guard($guard)->guest()) { return response('Unauthorized.', 401); } return $next($request); }
public function proposeSolution() { $questionId = Request::get('questionId'); $question = Question::find($questionId); $answers = $question->answers()->get()->toArray(); // Prepare array of proposed answers $proposedSolution = []; if ($question->question_type == 'one_variant') { $proposedSolution[] = (int) Request::get('chosenAnswer'); } else { $proposedSolution = Request::get('chosenAnswers'); } // Prepare array of correct answers $correctSolution = []; foreach ($answers as $answer) { if ($answer['is_correct']) { $correctSolution[] = $answer['id']; } } $proposedSolutionResult = $proposedSolution == $correctSolution; // pass to response detailed results on proposed solution $proposedSolutionWithDetailedResult = []; foreach ($proposedSolution as $answerId) { foreach ($answers as $answer) { if ($answer['id'] == $answerId) { $is_correct = $answer['is_correct']; } } $proposedSolutionWithDetailedResult[$answerId] = $is_correct; } if (\Auth::user()) { \Auth::user()->replies()->updateOrCreate(['question_id' => $questionId], ['is_correct' => $proposedSolutionResult]); } return response()->json(['correctSolution' => $correctSolution, 'proposedSolutionWithDetailedResult' => $proposedSolutionWithDetailedResult, 'proposedSolutionResult' => $proposedSolutionResult]); }
/** * Verify the incoming request's user has a subscription. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string $subscription * @param string $plan * @return \Illuminate\Http\Response */ public function handle($request, $next, $subscription = 'default', $plan = null) { if ($this->subscribed($request->user(), $subscription, $plan, func_num_args() === 2)) { return $next($request); } return $request->ajax() || $request->wantsJson() ? response('Subscription Required.', 402) : redirect('/settings#/subscription'); }
public function status($id) { $books = Books::find($id); $active = $books->active == true ? false : true; $books->update(['active' => $active]); return response()->json(['active' => $active]); }
public function clear() { parent::onlyAjax(); $this->authorize(PasswordResetsPolicy::PERMISSION_DELETE); PasswordReset::getTokenRepository()->deleteExpired(); return response()->json(['status' => 'success']); }
/** * @param Request $request * * @return \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ protected function createDefaultResponse($request) { if ($request->ajax()) { return response('', 200); } return redirect()->route('blog.admin.categories.index'); }
/** * Store a newly created MutipleAnswer in storage. * POST /mutipleAnswers * * @param Request $request * * @return Response */ public function store(Request $request) { if (sizeof(MutipleAnswer::$rules) > 0) { $this->validateRequestOrFail($request, MutipleAnswer::$rules); } $input = $request->all(); $decrypt = MCrypt::decrypt($input['answers']); $answers = json_decode($decrypt); return response()->json($answers); DB::beginTransaction(); foreach ($answers as $key => $value) { try { $check = MutipleAnswer::where('mutiple_question_id', $value->id)->where('user_id', $request->user_id)->count(); if ($check == 0) { $data['mutiple_question_id'] = $value->id; $data['answer'] = $value->answer; $data['user_id'] = $request->user_id; $mutipleAnswers = $this->mutipleAnswerRepository->create($data); } } catch (Exception $e) { DB::rollBack(); return response()->json('Something went wrong on server.', 500); } } DB::commit(); return response()->json("Your answers saved successfully"); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { // Check for the guard and redirect accordingly if (Auth::guard($guard)->guest()) { if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } elseif ($guard == 'student') { return redirect()->guest('/students/login'); } elseif ($guard == 'teacher') { return redirect()->guest('/teachers/login'); } elseif ($guard == 'hostelStaff') { return redirect()->guest('/hostelStaffs/login'); } elseif ($guard == 'libraryStaff') { return redirect()->guest('/libraryStaffs/login'); } elseif ($guard == 'departmentStaff') { return redirect()->guest('/departmentStaffs/login'); } elseif ($guard == 'chiefWardenStaff') { return redirect()->guest('/chiefWardenStaffs/login'); } elseif ($guard == 'adminStaff') { return redirect()->guest('/adminStaffs/login'); } elseif ($guard == 'admin') { return redirect()->guest('/admins/login'); } } return $next($request); }
/** * Store a newly created resource in storage. * * @return Response */ public function store(Request $request) { // error_log("------------------------------------------------------"); $Mailer = new Email(); $Mailer->email = $request['email']; /* $validator class with method fails() */ $validator = Validator::make($request->all(), ['email' => 'required|email']); /* $isNewEmail = true: no email found in db false: duplicate email found in db */ $isNewEmail = collect($Mailer->where('email', $Mailer->email)->get())->isEmpty() ? true : false; if ($validator->fails()) { error_log(json_encode(['error' => ['invalid_email' => $request->all()]])); return response()->json(['error' => 'E-mail is invalid'])->setCallback($request->input('callback')); } elseif (!$isNewEmail) { error_log(json_encode(['error' => ['duplicate_email' => $request->all()]])); return response()->json(['error' => 'E-mail is marked as being subscribed'])->setCallback($request->input('callback')); return redirect('/')->withErrors($validator)->withInput(); } else { error_log(json_encode(['mailer' => ['newEmail' => $Mailer]])); // soon $Scribe = $this->subscribe($Mailer->email); // soon error_log(json_encode(['scribe' => $Scribe])); $Mailer->save(); return response()->json(['success' => true])->setCallback($request->input('callback')); } }
public function index(Request $request) { if ($request->ajax()) { $reminders = PaymentDefaultReminder::all(); return response()->json($reminders); } }
public function display(Exception $exception, $code) { $class = $code == 404 ? 'page-404' : 'page-500'; $content = view('expendable::admin.errors.default', ['code' => $code, 'class' => $class, 'message' => $exception->getMessage()]); $this->layoutManager->add(['class_layout' => $class . '-full-page', 'content' => $content]); return response()->make($this->layoutManager->render(), $code); }
public function addPoint(Request $request) { $user = JWTAuth::parseToken()->authenticate(); $user->points = $user->points + $request->input('amount'); $user->save(); return response()->json(['success' => true, 'message' => "Users points added", 'users' => $user]); }
function index(Request $request) { ///////////////// // Load Filter // ///////////////// $filters = $this->request->only('type', 'tag', 'skip', 'take', 'group', 'with_count'); /////////// // Query // /////////// if (!$filters['take']) { $filters['take'] = 500; } else { $filters['take'] = min($filters['take'] * 1, 500); } $filters['skip'] = $filters['skip'] * 1; $q = Model::name($filters['name'])->type($filters['type']); if ($filters['group']) { $q = $q->groupby('tag'); } if ($filters['with_count']) { $count = $q->count(); } $data = $q->skip($filters['skip'])->take($filters['take'])->orderBy('tag')->select(['type', 'tag'])->get(); ////////////// // Response // ////////////// return response()->json(JSend::success(['count' => $count, 'data' => $data->toArray()])->asArray())->setCallback($this->request->input('callback')); }
public function store(Goal $goal, Request $request) { $attributes = $request->input('attributes'); $user = $request->user(); $newGoal = $user->goals()->create($attributes, ['is_admin' => true]); return response()->json(['data' => ['id' => $newGoal->id, 'type' => $newGoal->getType(), 'attributes' => ['title' => $newGoal->title, 'due_at' => $newGoal->due_at]]]); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->user()->admin) { return response("Nope.", 403); } return $next($request); }
public function validateMerchantOtp(request $request) { $apiKey = $request->only('api_key'); $validator = Validator::make($apiKey, ['api_key' => 'required']); if ($validator->fails()) { $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403); return $response; } $role = Role::find(2); $key = Config::get('custom.JWTkey'); $decoded = JWT::decode($apiKey['api_key'], $key, array('HS256')); if ($decoded->type != 'merchant') { return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403); } $user = User::find($decoded->sub); // check the current user if (empty($user) || !$user->hasRole(['merchant']) || !$user->status) { return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403); } $user_id = $user->id; $input = $request->only('otp'); $matchThese = ['user_id' => $user_id, 'code' => $input['otp']]; $sms = UserSmsCode::where($matchThese)->first(); if ($sms == '' || empty($sms)) { return response()->json(['response_code' => 'RES_IOG', 'messages' => 'Invalid OTP Given'], 422); } $sms->status = true; $sms->save(); $user->is_mobile_verified = true; $user->save(); return response()->json(['response_code' => 'RES_MV', 'messages' => 'Mobile Verified']); }