I’ve been trying to fix the init error for hours but it still doesn’t work. I’ve created a controller named JournalController.php
Why is my controller not working?
This is my code that error in "Target class [JournalController] does not exist". Actually on this page the display has appeared, but when the submit button is clicked. Then an error will appear that the Controller does not exist.
<form class="register-form" method="post" action="{{ route('journals.store') }}" enctype="multipart/form-data">
@csrf
<label>Post a Picture</label>
<input class="form-control" type="file" name="image" id="formFile">
<label>Place Name</label>
<input type="text" class="form-control" name="place" value="{{ old('place') }}" placeholder="Neuschwanstein">
<label>Country</label>
<input type="text" class="form-control" name="country" value="{{ old('country') }}" placeholder="Jerman">
<label>Date</label>
<input type="date" class="form-control"name="date" value="{{ old('date') }}">
<label>Experiences</label>
<input type="Text" class="form-control" name="experience" value="{{ old('experience') }}" placeholder="The most beautiful castle">
<button class="btn btn-danger btn-block btn-round" type="submit" href="{{ route('journals.create') }}"><i class="fa fa-plus"></i>Add</button>
</form>
This is my code that error in "Undefined variable $journals", The error is " @forelse ($journals as $journal)".
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>No.</th>
<th>Picture</th>
<th>Place</th>
<th>Country</th>
<th>Date</th>
<th>Experiences</th>
</tr>
</thead>
<tbody>
@forelse ($journals as $journal)
<tr>
<td>{{ $journal->id }}</td>
<td><img src="{{ asset($journal->image) }}" class="img-thumbnail" style="width:200px" />
</td>
<td>{{ $journal->place }}</td>
<td>{{ $journal->country }}</td>
<td>{{ $journal->date }}</td>
<td>{{ $journal->experience }}</td>
</tr>
@empty
<tr>
<td colspan="6">
No record found!
</td>
</tr>
@endforelse
</tbody>
</table>
And this is my Controller, I’ve tried the various methods that I listed here. But it hasn’t worked
public function index()
{
$journals = Journal::get();
return view('journals.index', ['journals' => $journals]);
return view('journals.index', compact('journals'));
return view('journals.index')->with('journals', $journals);
return view('journals.index', ['journals' => Journals::all(),]);
}
2
Answers
Could you please update your question providing your
routes > web.config
to see what is going on with the controller and routing issue.With the
Undefined variable
I tend to do the following when passing variables, even if there is just one as it looks better and if later down the line its easier to pass more variables.Laravel cannot find the specified controller class. The file should be named "JournalController.php" and should include the following.
Make sure to clear the cached routes and if the issues persists try running the following command to optimize your application’s autoload files: