I found several ways to do what I need to do, the first way was using the rounting using the web.php file. But according to serveral posts this creates vulnerabilities in the application. So I found out the correct usage is with a controller that manages the database queries.
I created a controller, named EventsController and put this into it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EventsController extends Controller
{
public function index()
{
$events = DB::table('eventaries')->select('id','coursname','start', 'end', 'category')->get();
return view('components.course-list')->with('eventaries', $events);
}
}
the blade is inside the folder: /resources/views/components/course-list.blade.php
Inside the blade I use this code:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $events->coursname}}
</div>
</div>
But I get the error:
Undefined variable $events (View: D:\laragon\www\censored\resources\views\components\course-list.blade.php)
CodePudding user response:
->with('eventaries', $events) means that you are passing the value of $events as eventaries. So in the blade you need to access it using $eventaries instead. So now blade code would be:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $eventaries->coursname}}
</div>
</div>
CodePudding user response:
You have given 'eventaries' as the name for events. So you can only access it with $eventaries within the view, not as events.
CodePudding user response:
you are passing to the view the value using the "with" method, and it does it like a value/key pair (->with($key, $value)). In your case you declare it like
return view('components.course-list')->with('eventaries', $events);
so, in the view you can access the value through the $eventaries, not the $events. Also, the query result is a collection and you will need to loop it to get each item
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
@foreach($eventaries as $event)
{{ $event->coursename }}
@endforeach
</div>
</div>
CodePudding user response:
When using the with
method on a view the first argument (key) becomes the name of the variable in the view and the second argument (value) becomes it's value.
This means you need to use $eventaries
in your view instead of $events
or rename the key in your controller return view('components.course-list')->with('events', $events);
.
Also, I'm not sure about defining the action directly in the routes file causes vulnerabilities. I just think that the routes file, which is often the first entry point for developers when exploring a Laravel app, becomes hard to read/manage.