<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sammar Ali on Medium]]></title>
        <description><![CDATA[Stories by Sammar Ali on Medium]]></description>
        <link>https://medium.com/@sammar.ali2439?source=rss-120e1331ae52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fB3wOZg2nPp5SYfG-f7WmQ.jpeg</url>
            <title>Stories by Sammar Ali on Medium</title>
            <link>https://medium.com/@sammar.ali2439?source=rss-120e1331ae52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:06:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sammar.ali2439/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Service and DTO pattern with Laravel]]></title>
            <link>https://medium.com/@sammar.ali2439/service-and-dto-pattern-with-laravel-16efd8b68b5c?source=rss-120e1331ae52------2</link>
            <guid isPermaLink="false">https://medium.com/p/16efd8b68b5c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Sammar Ali]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 18:06:23 GMT</pubDate>
            <atom:updated>2024-08-11T18:06:23.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k287S1qtCm9Z9pPxuur34Q.png" /></figure><p>Service and DTO patterns are a great way to keep your code maintainable and loosely coupled. In Laravel we often write our application logic in controller methods but it is not a great way to do so. Controller methods should be clean and they should call a service class to handle the logic instead. In this article, we see how we can use the service and DTO pattern to write more maintainable and loosely coupled code.</p><p>Let’s see an example of how a typical controller method looks alike.</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Post;<br><br>use Validator;<br>use Illuminate\Http\Request;<br>use App\Http\Controllers\Controller;<br><br>class PostController extends Controller<br>{<br>   <br>  public function store(Request $request)<br>    {<br>        // validating the fields<br>        $validator = Validator::make($request-&gt;all(), [<br>            &#39;title&#39; =&gt; &#39;required|string|max:255&#39;,<br>            &#39;body&#39; =&gt; &#39;required|string&#39;,<br>        ]);<br><br>        // returning error response if validation fails<br>        if ($validator-&gt;fails()) {<br>            return respone()-&gt;json([<br>                &#39;success&#39; =&gt; false,<br>                &#39;message&#39; =&gt; $validator-&gt;errors()-&gt;first(),<br>            ]);<br>        }<br><br>        // creating the post<br>        $post = Post::create([<br>            &#39;title&#39; =&gt; $request-&gt;title,<br>            &#39;body&#39; =&gt; $request-&gt;body,<br>        ]);<br><br>        // returning success response<br>        return response()-&gt;json([<br>            &#39;success&#39; =&gt; true,<br>            &#39;message&#39; =&gt; &#39;Post has been created successfully!&#39;,<br>            &#39;post&#39; =&gt; $post<br>        ]);<br>    }<br>    <br>}</pre><p>In the above controller store method, we are validating the fields in the request, creating the post, and returning the post in response.</p><p>Now let’s see how we can clean our controller method.</p><p><strong>Making the Request Class:-</strong></p><p>Make a separate request class for handling the store post request. In the request class, we handle field validations.</p><pre>php artisan make:request CreatePostRequest</pre><pre>&lt;?php<br><br>namespace App\Http\Requests\Post;<br><br>use Illuminate\Foundation\Http\FormRequest;<br>use Illuminate\Contracts\Validation\Validator;<br>use Illuminate\Http\Exceptions\HttpResponseException;<br><br>class CreatePostRequest extends FormRequest<br>{<br>    /**<br>     * Determine if the user is authorized to make this request.<br>     */<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    /**<br>     * Get the validation rules that apply to the request.<br>     *<br>     * @return array&lt;string, \Illuminate\Contracts\Validation\ValidationRule|array&lt;mixed&gt;|string&gt;<br>     */<br>    public function rules(): array<br>    {<br>        return [<br>            &#39;title&#39; =&gt; &#39;required|string|max:255&#39;,<br>            &#39;body&#39; =&gt; &#39;required|string|max:255&#39;,<br>        ];<br>    }<br><br>    // method for returning validation errors in json response<br>    public function failedValidation(Validator $validator)<br>    {<br>        // throwing exception in validation failed<br>        throw new HttpResponseException(<br>            // returing error validation responses in json<br>            response()-&gt;json([<br>                &#39;success&#39; =&gt; false,<br>                &#39;message&#39; =&gt; $validator-&gt;errors()-&gt;first(),<br>            ]),<br>        );<br>    }<br>}</pre><p><strong>The DTO (Data Transfer Objects) class:-</strong></p><p>DTOs are used to transfer data between different layers of applications. It helps to decouple these layers from one another. In this example, we want to transfer the validated data from our request class to our service class so we can make a DTO class to do so.</p><p><strong>Making the DTO class for creating posts:-</strong></p><p>we can create the DTO class under app/dtos folder.</p><pre>&lt;?php<br><br>namespace App\DataTransferObjects\Post;<br><br>use App\Http\Requests\Post\CreatePostRequest;<br><br>readonly class CreatePostDto<br>{<br>    public function __construct(<br>        public string $title,<br>        public string $body,<br>    ) {<br>    }<br><br>    // method for accepting data from the request<br>    public static function fromApiRequest(CreatePostRequest $request): CreatePostDto<br>    {<br>        return new self(<br>            $request-&gt;validated(&#39;title&#39;),<br>            $request-&gt;validated(&#39;body&#39;),<br>        );<br>    }<br>}</pre><p>We have created the fromApiRequest method which takes the CreatePostRequest and returns the new self-instance of validated data from the request.</p><p><strong>The Service Class:-</strong></p><p>The service class is responsible for handling the logic in this case the creation of the post. We can create a service class under the app/services folder.</p><p>Let’s create a service class named postService.php.</p><pre>&lt;?php<br><br>namespace App\Services\Post;<br><br>use App\Models\Post;<br>use App\Dtos\CreatePostDto;<br><br>class PostService {<br><br>    // method for creating the post<br>    public function createPost(CreatePostDto $createPostDto): Post {<br><br>        // creating the post<br>        $post = Post::create([<br>            &#39;title&#39; =&gt; $createPostDto-&gt;title,<br>            &#39;description&#39; =&gt; $createPostDto-&gt;description<br>        ]);<br><br>        // returing the created post<br>        return $post;<br>    }<br>}</pre><p>Now if you see the create post method accepting a CreatePostDto which we will pass when we call this method from our controller.</p><p>Now we have implemented the service and DTO classes let&#39;s see how our controller method looks now.</p><p><strong>Final Controller method:-</strong></p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Post;<br><br>use Validator;<br>use App\Http\Requests\CreatePostRequest;<br>use App\Http\Controllers\Controller;<br>use App\Dtos\CreatePostDto;<br>use App\Services\PostService;<br><br>class PostController extends Controller<br>{<br>    // injecting dependencies<br>    public function __construct(private readonly PostService $postService) {}<br>   <br>    public function store(CreatePostRequest $request): JsonResponse<br>    {<br>        // creating the post through post service<br>        $post = $this-&gt;postService-&gt;createPost(<br>            createPostDto: CreatePostDto::fromApiRequest($request)<br>        );<br>        <br>        // returning success response<br>        return response()-&gt;json([<br>            &#39;success&#39; =&gt; true,<br>            &#39;message&#39; =&gt; &#39;Post has been created successfully!&#39;,<br>            &#39;post&#39; =&gt; $post<br>        ]);<br>    }<br>    <br>}</pre><p>Now you can see our controller method become simpler and much cleaner. So now if you want to add more validations fields then these fields go into respective request classes, if you want to add more logic it will go into the service class method but your controller method always remains clean.</p><p>Moreover, we can also use these service methods in other places increasing the code reusability.</p><p><strong>Conclusion:-</strong></p><p>By adopting the Service and DTO patterns in Laravel, we can significantly enhance the maintainability and clarity of our code. Through the separation of concerns and decoupling of application layers, we can ensure that our controller methods remain concise and focused. Furthermore, the use of DTOs facilitates seamless data transfer between these layers, thereby improving the overall structure and organization of our code. This approach not only elevates code quality but also fosters reusability, simplifying the integration of our service methods into other parts of the application.</p><p>Happy coding ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16efd8b68b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>