【问题标题】:Laravel 8 ErrorException: Trying to access array offset on value of type nullLaravel 8 ErrorException:尝试访问 null 类型值的数组偏移量
【发布时间】:2020-11-09 23:09:23
【问题描述】:

我正在与 Laravel 合作开发我的项目,基本上我想根据我的主题从数据库中编辑一些 文章,所以我创建了一个名为 edit.blade.php 的刀片,在这个刀片中,有一个获取文章当前图像的行:

<div class="row">
    @foreach($article->images['images'] as $key => $image) 
        <div class="col-sm-2">
            <label class="control-label">
                {{$key}}
                <input type="radio" name="imagesThumb" value="{{ $image }}" {{ $article->images['thumb'] ? 'checked' : '' }} />
                <a href="{{$image}}"><img src="{{$image}}" width="100%"></a>
            </label>
        </div>
    @endforeach
</div>

Article 模型也是这样的:

class Article extends Model
{
    use HasFactory;
    use Sluggable;

    protected $guarded = [];

    protected $casts = [
        'images' => 'array'
    ];

    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }

    public function path()
    {
        return "/article/$this->slug";
    }
}

这里是调用刀片的ArticleController edit方法:

public function edit(Article $article)
{
    return view('website.backend.articles.edit',compact('article'));
}

现在的问题是,每当我想去这个刀片时,它都会返回这个错误:

ErrorException 试图访问 null 类型值的数组偏移量 (查看:edit.blade.php)

而且它指的是这一行刀片:

@foreach($article->images['images'] as $key => $image)

所以我不知道为什么它会显示这个错误,如果你知道请告诉我,我非常感谢你们的任何想法......

提前致谢。


更新 #2:

这是我的ArticleControllerstore方法:

public function store(ArticleRequest $request)
{
    //auth()->loginUsingId(1);
    $imageUrl = $this->uploadImages($request->file('images'));
    auth()->user()->article()->create(array_merge(['images' => $imageUrl], $request->all()));
    return redirect(route('articles.index'));
}

这是 UploadImages 方法附带的AdminController,并由ArticleController 扩展:

class AdminController extends Controller
{
    protected function uploadImages($file)
    {
        $year = Carbon::now()->year;
        $imagePath = "/upload/images/{$year}/";
        $filename = $file->getClientOriginalName();
        $file = $file->move(public_path($imagePath), $filename);
        $sizes = ["300","600","900"];
        $url['images'] = $this->resize($file->getRealPath(), $sizes, $imagePath, $filename);
        $url['thumb'] = $url['images'][$sizes[0]];
        return $url;
    }
    private function resize($path, $sizes, $imagePath, $filename)
    {
        $images['original'] = $imagePath . $filename;
        foreach($sizes as $size)
        {
            $images[$size] = $imagePath . "{$size}" . $filename;
            Image::make($path)->resize($size, null, function($constraint){
                $constraint->aspectRatio();
            })->save(public_path($images[$size]));
        }
        return $images;
    }
}

更新 #1:

dd($article); 的输出是:

    App\Models\Article {#1234 ▼
  #guarded: []
  #casts: array:1 [▼
    "images" => "array"
  ]
  #connection: "mysql"
  #table: "articles"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▼
    "id" => 2
    "user_id" => 1
    "title" => "asdasd"
    "slug" => "asdasd"
    "description" => "asdsadas"
    "body" => "asdsada"
    "images" => "F:\xampp\tmp\php1825.tmp"
    "tags" => "asdsad"
    "viewCount" => 0
    "commentCount" => 0
    "created_at" => "2020-11-09 12:24:33"
    "updated_at" => "2020-11-09 12:24:33"
  ]
  #original: array:12 [▼
    "id" => 2
    "user_id" => 1
    "title" => "asdasd"
    "slug" => "asdasd"
    "description" => "asdsadas"
    "body" => "asdsada"
    "images" => "F:\xampp\tmp\php1825.tmp"
    "tags" => "asdsad"
    "viewCount" => 0
    "commentCount" => 0
    "created_at" => "2020-11-09 12:24:33"
    "updated_at" => "2020-11-09 12:24:33"
  ]
  #changes: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

【问题讨论】:

  • 我没有看到 dd 的输出,但是我想应该是@foreach($article-&gt;images as $key =&gt; $image) 如果上面的方法失败了,然后贴出dd($article);的输出
  • @sta 我刚刚添加了它,请参阅更新 #1,谢谢。
  • 请编辑。折叠它#attributes: array:12 [▶]更新它
  • @sta 我刚刚折叠它并编辑了 UPDATE #1。
  • 根据您的代码,images 应该是一个数组,但它的字符串 "images" =&gt; "F:\xampp\tmp\php1825.tmp",它保存了 tmp 图像而不是正确的名称

标签: php laravel laravel-8


【解决方案1】:

因为这行:

auth()-&gt;user()-&gt;article()-&gt;create(array_merge(['images' =&gt; $imageUrl], $request-&gt;all()));

$request-&gt;all() 包含一个键 images,它设置为临时路径 (F:\xampp\tmp\php1825.tmp),在 array_merge 中,后面的参数中的值会覆盖早期参数中的值。要修复它,只需像这样交换参数:

auth()-&gt;user()-&gt;article()-&gt;create(array_merge($request-&gt;all(), ['images' =&gt; $imageUrl]));

【讨论】:

  • 你是我的英雄!非常感谢你
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 2021-01-09
  • 2021-07-23
  • 2020-09-10
  • 2022-12-18
  • 1970-01-01
相关资源
最近更新 更多