<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
timwassenburg / laravel-service-generator example snippets
artisan make:service {name}
artisan make:service {name}
namespace App\Services;
use App\Models\Post;
class PostService
{
// Declare the function as static
public static function getPostBySlug(string $slug): Post
{
return Post::with('tags')
->where('slug', $slug)
->get();
}
}
namespace App\Http\Controllers;
// Include the service
use App\Services\PostService;
class PostController extends Controller
{
public function show(string $slug)
{
// Call the method statically from the service class
$post = PostService::getPostBySlug($slug);
return view('posts.show', compact('post'));
}
}#
namespace App\Services;
use App\Models\Post;
class PostService
{
public function getPostBySlug(string $slug): Post
{
return Post::with('tags')
->where('slug', $slug)
->get();
}
}
namespace App\Http\Controllers;
// Include the service
use App\Services\PostService;
class PostController extends Controller
{
// Declare the property
protected $postService;
// Inject the service into the constructor
public function __construct(PostService $postService)
{
// Assign the service instance to the class property
$this->postService = $postService;
}
public function show($slug)
{
// Call the method you need from the service via the class property
$post = $this->postService->getPostBySlug($slug);
return view('posts.show', compact('post'));
}
}