#php #jquery #json #laravel-4
#php #jquery #json #laravel-4
Вопрос:
У меня есть довольно простой метод, который создает новую запись в таблице. Но я хочу, чтобы это действие разрешалось только зарегистрированным пользователям (Laravel / Confide). Все работает нормально, не проверяя, вошел ли пользователь в систему. Скрипт красиво возвращает строку JSON для моего вызова jQuery Ajax.
Но как только я добавляю проверку ‘if (Auth:: check ()’, я получаю огромную дополнительную строку в результате (полный класс пользователя !?!?! с прикрепленным к нему массивом в кодировке JSON), портит мой массив в кодировке JSON. Это нормальное поведение или я что-то здесь упускаю?
Это рабочий метод:
public function create()
{
//if(Auth::check()) {
//$userId = Auth::getUser()->id; // Get logged in user id
$folder = new Folder();
$folder->parent_id = Input::get('fid');
$folder->title = 'Nieuwe map';
$folder->alias = 'nieuwe-map-'.time();
//$folder->created_by = $userId;
$folder->save();
return Response::json(array('success'));
//} else {
//return Response::json(array('error'));
//}
}
Это результат:
["success"]
Когда я добавляю проверку подлинности, я получаю этот результат:
<!--
use IlluminateAuthUserInterface;
use IlluminateAuthRemindersRemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
} -->["success"]
Комментарии:
1. Не могли бы вы опубликовать содержимое вашего
json
файла просмотра? Если вы просто хотите отправить ответ json, не могли бы вы простоreturn Response::json('json' => ['success'] )
? gist.github.com/anonymous/01b39d781945fff6bdba2. <?php header(‘Content-type: application/json’); ?> {{ json_encode($json-файле) }}
3. Вы не должны делать такие вещи, как установка типа содержимого в ваших представлениях. Я не знаю всего процесса того, что laravel делает внутренне при ответе с помощью view, но велика вероятность, что вам помешает какая-то фоновая обработка. Вам было бы лучше использовать
Response::json()
. Посмотрите, работает ли код, который я предоставил в своем первом комментарии.4. Я пробовал Response::json() раньше. Это не сработало, поэтому я искал другие способы и попутно использовал глупые «решения» ;). Использование Response::json имеет ту же проблему, он отлично работает, но при вызове Auth::check() все это становится бесполезным.
Ответ №1:
Сначала я был убежден, что ошибка была в Confide. Но из-за отсутствия комментариев / ответов и того факта, что я ничего не смог найти об этом в Интернете, я погрузился в код. Результатом было 5 минут «работы», и я это исправил. Я совершил большую ошибку!
Я хотел сохранить старую пользовательскую модель на случай, если она понадобится мне в другой раз. Поэтому при установке Confide я изменил модель пользователя на:
<?php
use ZizacoConfideConfideUser;
class User extends ConfideUser {
}
?>
<!--
use IlluminateAuthUserInterface;
use IlluminateAuthRemindersRemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
} -->
Итак … вот оно. При вызове Auth:check() был напечатан код без комментариев: огромная ошибка 😉