如何使用助手通过 Laravel 中的控制器共享数据?
我正在尝试使用助手将变量从一个控制器方法临时存储到另一个控制器方法(同一控制器的)。我这样做是因为我通常不信任用户输入,因为他们可以通过表单/URL 传递不同的 ID,然后该函数就会运行。最终,我想使用类似的东西:
if (Context::getTale()->id === $tale->id) {
// code here
}
获取 Tale 对象
我的代码:
class Context
{
/**
* Current tale.
* @var Tale|null
*/
protected static ?Tale $tale = null;
/**
* Get current tale.
* @return Tale|null
*/
public static function getTale(): ?Tale
{
return self::$tale;
}
/**
* Set current tale.
* @param Tale|null $tale
* @return void
*/
public static function setTale(?Tale $tale): void
{
if ($tale === null) {
return;
}
self::$tale = $tale;
}
}
我已经在 config/app.php 中的别名下注册了 Context 类。
在我的控制器中:
public function show($id)
{
// stuff the controller does
Context::setTale($tale)
}
public function saveProgress()
{
// < Code to get the Tale from the DB using the id passed >
if (Context::getTale()->id === $tale->id) {
// do something
}
}
问题是每次我尝试从 saveProgress
的上下文中获取 $tale
时,它都会返回 null。
我做错了什么吗?
另外,我可以尝试使用会话来实现此目的,但这对用户输入安全吗?用户是否仍然可以从他/她的浏览器编辑数据?
编辑:调用了两个方法,我想使用相同的 ID。我希望它检查用户是否仍在阅读同一个故事(因为我不信任用户输入)。
I am trying to use a helper to temporarily store a variable from one controller method to another controller method (of the same controller). I am doing this because I normally don't trust user input, as they could just pass a different ID through the form/URL and the function will run. Eventually, I want to use something like:
if (Context::getTale()->id === $tale->id) {
// code here
}
To get the Tale object
My code:
class Context
{
/**
* Current tale.
* @var Tale|null
*/
protected static ?Tale $tale = null;
/**
* Get current tale.
* @return Tale|null
*/
public static function getTale(): ?Tale
{
return self::$tale;
}
/**
* Set current tale.
* @param Tale|null $tale
* @return void
*/
public static function setTale(?Tale $tale): void
{
if ($tale === null) {
return;
}
self::$tale = $tale;
}
}
I have registered the Context class in config/app.php under aliases.
In my controller:
public function show($id)
{
// stuff the controller does
Context::setTale($tale)
}
public function saveProgress()
{
// < Code to get the Tale from the DB using the id passed >
if (Context::getTale()->id === $tale->id) {
// do something
}
}
The problem is that every time I try to get the $tale
from the context in saveProgress
it returns null.
Am I doing something wrong?
Also, I could try and use a Session for this, but is that secure against user input? Is a user still able to edit the data from his/her browser?
Edit: Two methods are called and I want to use the same ID. I want this to check if the user is still reading the same tale (as I don't trust user input).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论