# Basic controllers
- Controllers are classes that are in charge of the grunt work of preparing the data to pass to the views
- Our goal is to move the logic (now in the file routes/web.php) to their corresponding controllers (opens new window)
- Make a new controller class with the terminal command
php artisan make:controller Admin/RecordController
$ php artisan make:controller Admin/RecordController
1
NAMING CONVENTIONS
The name of a controller equals the singular "object" name, starting with a capital letter (e.g. Record
), followed by Controller
REMARK
Several courses/programmers use the plural noun of the "object" in the controller name (e.g. RecordsController
), although this is in contrast to the approach used in the official Laravel documentation
- Open the controller Admin/RecordController.php (located in folder app/Http/Controllers/Admin)
- Namespacing is (automatically) taken care of
- The necessary imports (the statements with the keyword
use
) are included
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RecordController extends Controller
{
//
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
REMARK
Notice the use of backslashes (\
) in the namespace
and use
statements
- Migrate all the code of the (anonymous function in the) 'admin/records' route to a new method
index()
in this controller- Add a new, fourth record to ensure that this approach will work
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RecordController extends Controller
{
public function index()
{
$records = [
'Queen - Greatest Hits',
'The Rolling Stones - Sticky Fingers',
'The Beatles - Abbey Road',
'The Who - Tommy'
];
return view('admin.records.index', [
'records' => $records
]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- Call this method
index()
in the 'admin/records' route in the routes/web.php file:- Line 2: is the namespace (starting from App\Http\Controllers) and name of the controller (Admin\RecordController)
- Line 8: the second argument of the
Route::get()
method is an array:- the first element refers to the
RecordController
class - the second refers to the name of the method in that controller that has to be called (
index
)
- the first element refers to the
<?php
use App\Http\Controllers\Admin\RecordController;
...
Route::prefix('admin')->name('admin.')->group(function () {
Route::redirect('/', '/admin/records');
Route::get('records', [RecordController::class, 'index'])->name('records.index');
});
...
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- Check the result in a browser by visiting http://vinyl_shop.test/admin/records (opens new window)