wantsJson() public static method

Determine if the current request is asking for JSON in return.
public static wantsJson ( ) : boolean
return boolean
 /**
  * Start the creation of a new balance payment
  *   Details get posted into this method
  * @param $userId
  * @throws \BB\Exceptions\AuthenticationException
  * @throws \BB\Exceptions\FormValidationException
  * @throws \BB\Exceptions\NotImplementedException
  */
 public function store($userId)
 {
     $user = User::findWithPermission($userId);
     $this->bbCredit->setUserId($user->id);
     $requestData = \Request::only(['reason', 'amount', 'return_path', 'ref']);
     $amount = $requestData['amount'] * 1 / 100;
     $reason = $requestData['reason'];
     $returnPath = $requestData['return_path'];
     $ref = $requestData['ref'];
     //Can the users balance go below 0
     $minimumBalance = $this->bbCredit->acceptableNegativeBalance($reason);
     //What is the users balance
     $userBalance = $this->bbCredit->getBalance();
     //With this payment will the users balance go to low?
     if ($userBalance - $amount < $minimumBalance) {
         if (\Request::wantsJson()) {
             return \Response::json(['error' => 'You don\'t have the money for this'], 400);
         }
         \Notification::error("You don't have the money for this");
         return \Redirect::to($returnPath);
     }
     //Everything looks gooc, create the payment
     $this->paymentRepository->recordPayment($reason, $userId, 'balance', '', $amount, 'paid', 0, $ref);
     //Update the users cached balance
     $this->bbCredit->recalculate();
     if (\Request::wantsJson()) {
         return \Response::json(['message' => 'Payment made']);
     }
     \Notification::success("Payment made");
     return \Redirect::to($returnPath);
 }
 /**
  * Start the creation of a new gocardless payment
  *   Details get posted into this method and the redirected to gocardless
  * @param $userId
  * @throws \BB\Exceptions\AuthenticationException
  * @throws \BB\Exceptions\FormValidationException
  * @throws \BB\Exceptions\NotImplementedException
  */
 public function store($userId)
 {
     User::findWithPermission($userId);
     $requestData = \Request::only(['reason', 'amount', 'return_path', 'stripeToken', 'ref']);
     $stripeToken = $requestData['stripeToken'];
     $amount = $requestData['amount'];
     $reason = $requestData['reason'];
     $returnPath = $requestData['return_path'];
     $ref = $requestData['ref'];
     try {
         $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => "gbp", "card" => $stripeToken, "description" => $reason));
     } catch (\Exception $e) {
         \Log::error($e);
         if (\Request::wantsJson()) {
             return \Response::json(['error' => 'There was an error confirming your payment'], 400);
         }
         \Notification::error("There was an error confirming your payment");
         return \Redirect::to($returnPath);
     }
     //Replace the amount with the one from the charge, this prevents issues with variable tempering
     $amount = $charge->amount / 100;
     //Stripe don't provide us with the fee so this should be OK
     $fee = $amount * 0.024 + 0.2;
     $this->paymentRepository->recordPayment($reason, $userId, 'stripe', $charge->id, $amount, 'paid', $fee, $ref);
     if (\Request::wantsJson()) {
         return \Response::json(['message' => 'Payment made']);
     }
     \Notification::success("Payment made");
     return \Redirect::to($returnPath);
 }
 protected function get_return_format()
 {
     if (Request::wantsJson()) {
         return 'json';
     }
     return self::$default_return_type;
 }
Example #4
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $logs = Log::find($id);
     if (\Request::wantsJson()) {
         return $logs->toJson();
     }
     dd($logs->toArray());
 }
 /**
  * Register the ApiProxy error handlers
  * @return void
  */
 private function registerErrorHandlers()
 {
     $this->app->error(function (ProxyException $ex) {
         if (\Request::ajax() && \Request::wantsJson()) {
             return new JsonResponse(['error' => $ex->errorType, 'error_description' => $ex->getMessage()], $ex->httpStatusCode, $ex->getHttpHeaders());
         }
         return \View::make('api-proxy-laravel::proxy_error', array('header' => $ex->getHttpHeaders()[0], 'code' => $ex->httpStatusCode, 'error' => $ex->errorType, 'message' => $ex->getMessage()));
     });
 }
 public function unauth()
 {
     if (\Auth::check()) {
         return false;
     }
     if (\Request::wantsJson()) {
         return json_encode(['error' => 'need login']);
     } else {
         return redirect('/auth/login');
     }
 }
Example #7
0
 protected function json_or_dd($data, $only_data = true)
 {
     if ($data instanceof Collection) {
         $array = $data->toArray();
     } elseif ($data instanceof Model) {
         $array = $data->toArray();
     } else {
         $array = $data;
     }
     if (\Request::wantsJson() || !env('APP_DEBUG', false)) {
         die(json_encode($array));
     }
     if ($only_data) {
         dd($array);
     }
     dd($data);
 }
 /**
  * Display a listing of tags
  *
  * @return Response
  */
 public function index()
 {
     $search = Input::get('search');
     if ($search) {
         $query = Tag::with('user')->where('title', 'LIKE', '%' . $search . '%')->orWhere('body', 'LIKE', '%' . $search . '%');
     } else {
         $query = Tag::with('user');
     }
     $query = $query->orderBy('created_at', 'desc');
     if (Request::wantsJson()) {
         $tags = $query->get();
         return Response::json(['tags' => $tags]);
     } else {
         $tags = $query->paginate(4);
         return View::make('tags.index')->with(['tags' => $tags, 'search' => $search]);
     }
 }
Example #9
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $query = Post::with('user');
     $tags = Tag::with('posts')->paginate(8);
     $parsedown = new Parsedown();
     // $converter = new CommonMarkConverter();
     if (Input::has('search')) {
         $search = Input::get('search');
         $query->where('title', 'like', "%{$search}%")->orWhere('content', 'like', "%{$search}%");
     }
     $query->orderBy('created_at', 'desc');
     if (Request::wantsJson()) {
         $posts = $query->get();
         return Response::json(['posts' => $posts, 'tags' => $tags]);
     } else {
         $posts = $query->paginate(4);
         return View::make('posts.index', compact('posts', 'tags', 'parsedown'));
     }
 }
Example #10
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $query = Post::with('user');
     //query builder
     if (Input::has('search')) {
         $search = Input::get('search');
         $query->where('title', 'like', '%' . $search . '%');
         $query->orWhere('description', 'like', '%' . $search . '%');
         $query->orWhereHas('user', function ($q) {
             $search = Input::get('search');
             $q->where('email', 'like', '%' . $search . '%');
             $q->orWhere('first_name', 'like', '%' . $search . '%');
             $q->orWhere('last_name', 'like', '%' . $search . '%');
         });
     }
     if (Request::wantsJson()) {
         $posts = $query->orderBy('created_at', 'desc')->get();
         return Response::json($posts);
     } else {
         $posts = $query->orderBy('created_at', 'desc')->paginate(3);
         return View::make('posts.index', array('posts' => $posts));
     }
 }
Example #11
0
 Route::get('/', ['uses' => 'UsersController@index']);
 Route::get('{username}', ['uses' => 'UsersController@show']);
 Route::post('{id}', ['uses' => 'UsersController@update', 'as' => 'user.update']);
 Route::get('{username}/itineraries/shared', function ($username) {
     $user = User::findFromData($username);
     $itineraries = $user->getSharedItineraries()->get();
     return $itineraries;
 });
 Route::get('{username}/itineraries', function ($username) {
     $user = User::findFromData($username);
     return $user->itinerariesWithSpotIds();
     // ->each(function(&$item) {
     // 	$item->isMine = $item->isMine();
     // });
     return $itineraries;
     if (Request::wantsJson()) {
         return $itineraries;
     }
     return View::make('site.itineraries.index', ['user' => $user, 'itineraries' => $itineraries]);
 });
 Route::get('{username}/itineraries/{id}', function ($username, $id) {
     $user = User::findFromData($username);
     $itinerary = Itinerary::find($id);
     return View::make('site.itineraries.show', ['user' => $user, 'itinerary' => $itinerary]);
 });
 Route::get('{username}/itineraries/{id}/edit', function ($username, $id) {
     return Redirect::to('/admin/itinerary/' . $id);
 });
 Route::get('{username}/itineraries/{id}/categories', function ($username, $id) {
     $user = User::findFromData($username);
     $itinerary = Itinerary::find($id);
 /**
  * Display the specified resource.
  *
  * @param int $id
  *
  * @return Response
  */
 public function show($id)
 {
     $category = Category::find($id)->withFamilyTree()->withParentTree();
     if (\Request::wantsJson()) {
         return $category->toJson();
     }
     $panel = ['left' => ['width' => '2'], 'center' => ['width' => '10']];
     return view('categories.show', compact('category', 'panel'));
     //Vista a categoria unica
 }
Example #13
0
/**
 * true if HTTP Accept header is application/json
 *
 * @return boolean
 */
function zbase_is_json()
{
    if (zbase_request_query_input('jsonp', false)) {
        return true;
    }
    if (zbase_request_query_input('json', false)) {
        return true;
    }
    if (zbase_is_post() && zbase_request_input('json', false)) {
        return true;
    }
    return \Request::wantsJson();
}
 public function destroy($id)
 {
     $post = Post::find($id);
     $post->delete();
     $message = 'Post was deleted';
     if (Request::wantsJson()) {
         return Response::json(array('message' => $message));
     } else {
         Session::flash('successMessage', $message);
         return Redirect::action('PostsController@index');
     }
 }
 /**
  * Remove the specified resource from storage.
  * DELETE /location/{id}
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     $location = CalendarEvent::find($id);
     $location->delete();
     // Modify destroy() to send back JSON if it's been requested
     if (Request::wantsJson()) {
         return Response::json(array('Response', "Good!"));
     } else {
         return Redirect::action('LocationController@index');
     }
 }
 public function validateAndSave($event, $location)
 {
     try {
         $uploads_directory = 'images/uploads/';
         if (Input::hasFile('event_image')) {
             $filename = Input::file('event_image')->getClientOriginalName();
             $event->event_image = Input::file('event_image')->move($uploads_directory, $filename);
         }
         if (Input::get('location') == '-1') {
             $location->location_name = Input::get('location_name');
             $location->location_street = Input::get('location_street');
             $location->location_city = Input::get('location_city');
             $location->location_state = Input::get('location_state');
             $location->location_zip = Input::get('location_zip');
             $location->saveOrFail();
         } else {
             $location = Location::findOrFail(Input::get('location'));
         }
         $event->start_time = Input::get('start_time');
         $event->end_time = Input::get('end_time');
         $event->event_name = Input::get('event_name');
         $event->description = Input::get('description');
         $event->cost = Input::get('cost');
         $event->location_id = $location->id;
         $event->creator_id = Auth::id();
         $event->saveOrFail();
         if (Request::wantsJson()) {
             return Response::json(array('Status' => 'Request Succeeded'));
         } else {
             Session::flash('successMessage', 'Your event has been successfully saved.');
             return Redirect::action('CalendarEventsController@show', array($event->id));
         }
     } catch (Watson\Validating\ValidationException $e) {
         Session::flash('errorMessage', 'Ohh no! Something went wrong. You should be seeing some errors down below.');
         Log::info('Validator failed', Input::all());
         return Redirect::back()->withInput()->withErrors($e->getErrors());
     }
 }
 public function validateAndSave($event, $location)
 {
     try {
         if (Input::get('location_dropdown') == '-1') {
             $location->title = Input::get('location');
             $location->address = Input::get('address');
             $location->city = Input::get('city');
             $location->state = Input::get('state');
             $location->zip = Input::get('zip');
             $location->saveOrFail();
         } else {
             $location = Location::findOrFail(Input::get('location_dropdown'));
         }
         $game = Game::firstOrCreate(array("device" => Input::get('console'), "genre" => Input::get('genre'), "game_title" => Input::get('game')));
         $event->start_time = Input::get('start_time');
         $event->end_time = Input::get('end_time');
         $event->title = Input::get('title');
         $event->description = Input::get('description');
         $event->price = Input::get('price');
         $event->location_id = $location->id;
         $event->game_id = $game->id;
         $event->user_id = Auth::id();
         $event->saveOrFail();
         if (Request::wantsJson()) {
             return Response::json(array('Status' => 'Request Succeeded'));
         } else {
             Session::flash('successMessage', 'Your event has been successfully saved.');
             return Redirect::action('CalendarEventsController@show', array($event->id));
         }
     } catch (Watson\Validating\ValidationException $e) {
         Session::flash('errorMessage', 'Ohh no! Something went wrong. You should be seeing some errors down below.');
         Log::info('Validation failed', Input::all());
         return Redirect::back()->withInput()->withErrors($e->getErrors());
     }
 }
Example #18
0
 public function validateAndSave($user)
 {
     try {
         $uploads_directory = 'images/uploads/';
         if (Input::hasFile('profile_picture')) {
             $filename = Input::file('profile_picture')->getClientOriginalName();
             $user->profile_picture = Input::file('profile_picture')->move($uploads_directory, $filename);
         } else {
             $user->profile_picture = "http://lorempixel.com/200/200/sports/8/";
         }
         $user->first_name = Input::get('first_name');
         $user->last_name = Input::get('last_name');
         $user->city = Input::get('city');
         $user->zip = Input::get('zip');
         $user->email = Input::get('email');
         $user->gender = Input::get('gender');
         $user->username = Input::get('username');
         $user->password = Input::get('password');
         $user->password_confirmation = Input::get('password_confirmation');
         $user->saveOrFail();
         /* Laravel automatically calls set SportsListAttriute - tagging favorite sports*/
         $user->sports_list = Input::get('sports_list');
         if (Request::wantsJson()) {
             return Response::json(array('Status' => 'Request Succeeded'));
         } else {
             Session::flash('successMessage', 'Your Player has been successfully saved.');
             return Redirect::action('UsersController@show', array($user->id));
         }
     } catch (Watson\Validating\ValidationException $e) {
         Session::flash('errorMessage', 'Ohh no! Something went wrong. You should be seeing some errors down below.');
         Log::info('Validator failed', Input::all());
         return Redirect::back()->withInput()->withErrors($e->getErrors());
     }
 }
Example #19
0
 public function delete($id)
 {
     $wantsJson = Request::wantsJson();
     $asset = Asset::find($id);
     if ($asset == null) {
         return $wantsJson ? Response::json(['errors' => 'No asset found', 'status' => 404, 'id' => $id]) : Redirect::back()->with(['errors' => 'No asset found', 'status' => 404]);
     }
     if (Schema::hasTable('assetables')) {
         $total = 0;
         $assetables = DB::table('assetables')->where('asset_id', $id)->get();
         if ($assetables) {
             $item = null;
             foreach ($assetables as $as) {
                 $as_type = $as->assetable_type;
                 $as_id = $as->assetable_id;
                 $item = $as_type::find($as_id);
                 if ($item) {
                     $item->assets()->detach($asset);
                     $total = $item->assets->count();
                 }
             }
         }
     }
     $asset->delete();
     return $wantsJson ? Response::json(['notice' => 'Asset deleted', 'status' => 200, 'id' => $id]) : Redirect::back()->with(['error' => 'Asset deleted', 'status' => 200, 'id' => $id]);
 }
Example #20
0
 public function errorResponse($message)
 {
     $wantsJson = Request::wantsJson();
     $backurl = URL::previous() . "#form-message";
     return $wantsJson ? Response::json(['errors' => $message], 400) : Redirect::to($backurl)->with(['errors' => $message])->withInput();
 }
 /**
  * Parses raw blog posts, performs wardrobe level and application level parsing
  * @return string
  */
 public function processParseBlogPostContent()
 {
     if (!\Request::wantsJson() && !\Request::ajax()) {
         \App::abort(404);
     }
     $content = \Input::get('content');
     return \BlogPostParser::parse(md($content), '*****@*****.**');
 }
 public function validateAndSave($event, $location)
 {
     try {
         $uploads_directory = 'images/uploads/';
         if (Input::hasFile('event_image')) {
             $filename = Input::file('event_image')->getClientOriginalName();
             $event->event_image = Input::file('event_image')->move($uploads_directory, $filename);
         } else {
             $event->event_image = "http://lorempixel.com/200/200/sports/19/";
         }
         $location->name_of_location = Input::get('name_of_location');
         $location->address = Input::get('address');
         $location->city = Input::get('city');
         $location->zip = Input::get('zip');
         $location->phone = Input::get('phone');
         $location->url = Input::get('url');
         $location->saveOrFail();
         $event->start_time = Input::get('start_time');
         $event->end_time = Input::get('end_time');
         $event->event_name = Input::get('event_name');
         $event->description = Input::get('description');
         $event->amount = Input::get('amount');
         $event->location_id = $location->id;
         $event->sport_id = Input::get('select_sport');
         $event->organizer_id = Auth::id();
         $event->skill_level = Input::get('select_skill_level');
         $event->event_image = Input::get('event_image');
         $event->saveOrFail();
         if (Request::wantsJson()) {
             return Response::json(array('Status' => 'Request Succeeded'));
         } else {
             Session::flash('successMessage', 'Your event has been successfully saved.');
             return Redirect::action('GameEventsController@show', array($event->id));
         }
     } catch (Watson\Validating\ValidationException $e) {
         Session::flash('errorMessage', 'Ohh no! Something went wrong. You should be seeing some errors down below.');
         Log::info('Validator failed', Input::all());
         return Redirect::back()->withInput()->withErrors($e->getErrors());
     }
 }
 public function pay_record()
 {
     if (Request::wantsJson()) {
         return $this->pay_record_json();
     } else {
         return $this->pay_record_html();
     }
 }
 public function getTransFilters()
 {
     $filter = null;
     $regex = null;
     if (\Request::has('filter')) {
         $filter = \Request::get("filter");
         $this->transFilters['filter'] = $filter;
     }
     $regex = \Request::get("regex", null);
     if ($regex !== null) {
         $this->transFilters['regex'] = $regex;
     }
     \Cookie::queue($this->cookieName(self::COOKIE_TRANS_FILTERS), $this->transFilters, 60 * 24 * 365 * 1);
     if (\Request::wantsJson()) {
         return \Response::json(array('status' => 'ok', 'transFilters' => $this->transFilters));
     }
     return !is_null(\Request::header('referer')) ? \Redirect::back() : \Redirect::to('/');
 }
 public function adminUpdate($id)
 {
     $user = User::findWithPermission($id);
     $madeTrusted = false;
     if (\Input::has('trusted')) {
         if (!$user->trusted && \Input::get('trusted')) {
             //User has been made a trusted member
             $madeTrusted = true;
         }
         $user->trusted = \Input::get('trusted');
     }
     if (\Input::has('key_holder')) {
         $user->key_holder = \Input::get('key_holder');
     }
     if (\Input::has('induction_completed')) {
         $user->induction_completed = \Input::get('induction_completed');
     }
     if (\Input::has('profile_photo_on_wall')) {
         $profileData = $user->profile()->first();
         $profileData->profile_photo_on_wall = \Input::get('profile_photo_on_wall');
         $profileData->save();
     }
     if (\Input::has('photo_approved')) {
         $profile = $user->profile()->first();
         if (\Input::get('photo_approved')) {
             $this->userImage->approveNewImage($user->hash);
             $profile->update(['new_profile_photo' => false, 'profile_photo' => true]);
         } else {
             $profile->update(['new_profile_photo' => false]);
             event(new MemberPhotoWasDeclined($user));
         }
     }
     $user->save();
     if (\Input::has('approve_new_address')) {
         if (\Input::get('approve_new_address') == 'Approve') {
             $this->addressRepository->approvePendingMemberAddress($id);
         } elseif (\Input::get('approve_new_address') == 'Decline') {
             $this->addressRepository->declinePendingMemberAddress($id);
         }
     }
     if ($madeTrusted) {
         $message = 'You have been made a trusted member at Build Brighton';
         $notificationHash = 'trusted_status';
         Notification::logNew($user->id, $message, 'trusted_status', $notificationHash);
         event(new MemberGivenTrustedStatus($user));
     }
     if (\Request::wantsJson()) {
         return \Response::json('Updated', 200);
     } else {
         \Notification::success('Details Updated');
         return \Redirect::route('account.show', [$user->id]);
     }
 }
Example #26
0
 public function topic()
 {
     $topic_id = Input::get('topic_id');
     $topic = Topic::find($topic_id);
     if (!isset($topic)) {
         if (Request::wantsJson()) {
             return Response::json(array('errCode' => 1, 'message' => 该专题不存在));
         } else {
             return Response::view('errors.missing');
         }
     }
     $gifts = Gift::where('topic_id', '=', $topic->id)->get();
     if (isset($gifts)) {
         $number = 1;
         foreach ($gifts as $gift) {
             $url = GiftPoster::where('gift_id', '=', $gift->id)->first()->url;
             $gift->img = StaticController::imageWH($url);
             $gift->number = $number++;
         }
     }
     $gifts = $this->isGiftLike($gifts);
     $type = $this->isTopicLike($topic_id);
     if (Request::wantsJson()) {
         return Response::json(array('errCode' => 0, 'message' => '返回专题页数据', 'topic' => $topic, 'gifts' => $gifts, 'type' => $type));
     }
     return View::make('index/goodsList')->with(array('topic' => $topic, 'gifts' => $gifts, 'type' => $type));
 }
 public function validateAndSave($post)
 {
     // create the validator
     $validator = Validator::make(Input::all(), Post::$rules);
     // attempt validation
     if ($validator->fails()) {
         Session::flash('errorMessage', 'Ohh no! Something went wrong...You should be seeing some errors down below...');
         Log::info('Validator failed', Input::all());
         // validation failed, redirect to the post create page with validation errors and old inputs
         return Redirect::back()->withInput()->withErrors($validator);
     } else {
         if (Input::hasFile('image')) {
             $file = Input::file('image');
             $post->uploadImage($file);
         }
         $post->title = Input::get('title');
         $post->body = Input::get('body');
         $post->user_id = Auth::id();
         $post->save();
         if (Entrust::hasRole('guest')) {
             $guest = Role::where('name', 'guest')->firstOrFail();
             Entrust::user()->detachRole($guest);
         }
         if (Request::wantsJson()) {
             return Response::json(array('Status' => 'Request Succeeded'));
         } else {
             Session::flash('successMessage', 'Your post has been successfully saved.');
             return Redirect::action('PostsController@show', array($post->id));
         }
     }
 }
Example #28
0
 public function destroy($id)
 {
     // ...
     // Modify destroy() to send back JSON if it's been requested
     if (Request::wantsJson()) {
         return Response::json(array('return' => 'deleted'));
     } else {
         return Redirect::action('PostsController@index');
     }
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     try {
         $group = Group::findOrFail($id);
         //prepare the meeting time for user friendly display
         $meetingTime = substr($group->meeting_time, 0, 1) == '0' ? substr($group->meeting_time, 1, 1) : substr($group->meeting_time, 0, 2);
         $group->meeting_time = $meetingTime . ':' . substr($group->meeting_time, -2, 2);
         $nextMeeting = $this->determineNextMeetingDate($group);
         if (Request::wantsJson()) {
             return Response::json(['group' => $group, 'nextMeeting' => $nextMeeting->toFormattedDateString()]);
         } else {
             return View::make('groups.show')->with(['group' => $group, 'nextMeeting' => $nextMeeting->toFormattedDateString()]);
         }
     } catch (Exception $e) {
         Log::error('Failed to find a specific record', array(404, "group: " . $group));
         App::abort(404);
         //this goes directly to the missing method in global.php
     }
 }
Example #30
0
 /**
  * Asking if the request is a type of AJAX request.
  *
  * @param  \Illuminate\Http\Request $request
  *
  * @return bool
  */
 protected function areYouAnAjax(Request $request)
 {
     return $request->ajax() || $request->wantsJson() || $request->acceptsJson() || $request->isJson();
 }