为了账号安全,请及时绑定邮箱和手机立即绑定

以旧值显示 Blade Laravel 中不同输入字段的数据库中的用户现有数据

以旧值显示 Blade Laravel 中不同输入字段的数据库中的用户现有数据

PHP
HUX布斯 2023-07-21 16:11:54
当我在编辑之前尝试在输入字段中显示现有数据时,收到此错误“尝试获取非对象的属性“帖子”(视图:E:\Projects\htdocs\zipad\resources\views\posts\edit.blade.php)”但是,当我尝试下面的代码时,它工作得很好Blade 中的工作代码    @foreach($user->posts as $post)<div class="col-4"> {{$post->about }}</div>@endforeach编辑.blade.php    <form action="/p" enctype="multipart/form-data" method="post">@csrf<div class="col-8 offset-2"><div class="form-group row">                            <label for="about" class="col-md-4 col-form-label text-md-right">{{ __(' post about') }}</label>                            <div class="col-md-6">                                <input id="about" type="text" class="form-control @error('about') is-invalid @enderror" name="about"  value="{{ old('about') ?? $user->posts->about }}" required autocomplete="about" autofocus>                                @error('about')                                    <span class="invalid-feedback" role="alert">                                        <strong>{{ $message }}</strong>                                    </span>                                @enderror                            </div>                            <label for="image" class="col-md-4 col-form-label text-md-right">{{ __(' post image') }}</label>                            <input type="file", class="form-control-file" id ="image" name="image">                            @error('image')                                    <div class="invalid-feedback" role="alert">                                        <strong>{{ $message }}</strong> </div>                                                                    @enderror                                <div class="btn btn-primary">                                <button> add img post</button>                                </div>                        </div></div>    </form>后置控制器public function edit(User $user){    return view('posts.edit', compact('user'));}
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

当您迭代时,$user->posts它会起作用,因为您正在访问每个帖子并渲染它。


但在您posts.edit使用时$user->posts->about,它不知道哪篇文章是关于哪篇文章的。


解决方案: 您必须像您提供的工作代码一样迭代该用户的所有帖子。


.....

@foreach($user->posts as $post)

<label for="about" class="col-md-4 col-form-label text-md-right">{{ __(' post about') }}</label>

<div class="col-md-6">

    <input id="about" type="text" class="form-control @error('about') is-invalid 

    @enderror" name="about"  value="{{ old('about') ?? $post->about }}" 

    required autocomplete="about" autofocus>

    @error('about')

    <span class="invalid-feedback" role="alert">

    <strong>{{ $message }}</strong>

    </span>

    @enderror

</div>

@endforeach

....


查看完整回答
反对 回复 2023-07-21
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信