It looks like the issue is with the way you're trying to populate the $projects and $posts variables and how you're using them in your Blade view. The error message you're getting suggests that $projects or $posts is null when you're trying to iterate over it with foreach.
Here's a revised version of your Livewire component and Blade view that should fix the issue:
Livewire Component:
<?php
namespace App\Http\Livewire\Design;
// ... other use statements ...
class Create extends Component
{
// ... other properties ...
public $selectedProjectId = null; // Add a property for the selected project ID
// ... other methods ...
public function mount(Design $design)
{
$this->design = $design;
$this->projects = Project::all(); // Load all projects
$this->posts = collect(); // Initialize posts as an empty collection
$this->initListsForFields();
}
public function updatedSelectedProjectId($projectId)
{
$this->posts = Post::where('project_id', $projectId)->get(); // Update posts based on selected project
}
// ... other methods ...
}
Blade View:
<form wire:submit.prevent="submit" class="pt-3">
<div class="form-group {{ $errors->has('design.project_id') ? 'invalid' : '' }}">
<label class="form-label" for="project">{{ trans('cruds.design.fields.project') }}</label>
<select wire:model="selectedProjectId" name="project"
class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
required>
<option value="">-- choose project --</option>
@foreach ($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
@endforeach
</select>
<div class="validation-message">
{{ $errors->first('design.project_id') }}
</div>
<div class="help-block">
{{ trans('cruds.design.fields.project_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('design.post_id') ? 'invalid' : '' }}">
<label class="form-label" for="post">{{ trans('cruds.design.fields.post') }}</label>
<select wire:model="design.post_id" name="post"
class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400" required>
@foreach ($posts as $post)
<option value="{{ $post->id }}">{{ $post->title }}</option>
@endforeach
</select>
<div class="validation-message">
{{ $errors->first('design.post_id') }}
</div>
<div class="help-block">
{{ trans('cruds.design.fields.post_helper') }}
</div>
</div>
</form>
Make sure to update the wire:model in the project <select> to selectedProjectId and in the post <select> to design.post_id. Also, ensure that the updatedSelectedProjectId method is named correctly to match the Livewire's automatic convention for updating properties (i.e., updated followed by the CamelCase name of the property).
This should resolve the foreach() error and allow you to select a project and dynamically load the related posts.