# Controller structure

You can create a new controller by running:

php tea make:controller name=ProductController

<?php

namespace App\Http\Controllers;

class ProductController extends Controller
{
}
1
2
3
4
5
6
7

You don't have to, but it is a good idea to follow REST actions:

<?php

namespace App\Http\Controllers;

use Devlob\Request\Request;

class ProductController extends Controller
{
    public function index()
    {   
    }

    public function store(Request $request)
    {   
    }

    public function show(int $id)
    {   
    }

    public function update(Request $request, int $id)
    {   
    }

    public function destroy(int $id)
    {   
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# Calling a controller action

Inside api.php you can call a controller action like this:

$router->get('/products/{id}', 'ProductController@show');
1

# Helper methods

app/Http/Controllers/Controller.php comes with two helper methods, notFound and deleted.

Both methods accept a second argument for a custom message.

If you need more freedom over these functions, then you can easily change them.

If you need more controller helper methods, then add them inside app/Http/Controllers/Controller.php.

Usage of notFound and deleted:

public function destroy(int $id)
{
    if ( ! $product = Product::find($id)) {
        return $this->notFound();
    }

    if ($product->delete()) {
        return $this->deleted();
    }

    return json(['Product could not be deleted'], 500);
}
1
2
3
4
5
6
7
8
9
10
11
12