Skip to content

Commit

Permalink
outsource method
Browse files Browse the repository at this point in the history
  • Loading branch information
fr0tt committed Aug 11, 2023
1 parent 5b72e3f commit 081db3b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
29 changes: 11 additions & 18 deletions app/Http/Controllers/TagController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
namespace App\Http\Controllers;

use App\Models\PostTag;
use App\Services\TagService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Tag;

class TagController extends Controller
{

private $service;

public function __construct()
{
$this->service = new TagService();
}

public function index()
{
$tags = Tag::where('user_id', Auth::user()->id)->orderBy('name')->get();
Expand All @@ -33,22 +41,22 @@ public function store(Request $request)
{

$this->validate($request, [
'name' => 'required_without:tags|string',
'name' => 'required_without:tags|string',
'tags.*.name' => 'required_without:name|string',
]);

$user_id = Auth::user()->id;
$tags = [];

if (isset($request->name)) {
$tag = $this->saveTag($request->name, $user_id);
$tag = $this->service->saveTag($request->name, $user_id);
if ($tag) {
return response()->json(['data' => $tag], 201);
}
return response()->json('Tag does already exist', 400);
} else if (isset($request->tags)) {
foreach ($request->tags as $tag_request_object) {
$tag = $this->saveTag($tag_request_object['name'], $user_id);
$tag = $this->service->saveTag($tag_request_object['name'], $user_id);
if ($tag) {
$tags[] = $tag;
}
Expand Down Expand Up @@ -91,19 +99,4 @@ public function destroy($id)
return response()->json('', 204);
}

private function saveTag(string $name, int $user_id)
{
if (Tag::where('name', $name)
->where('user_id', $user_id)->exists()
) {
return null;
}

$tag = Tag::create([
'name' => $name,
'user_id' => $user_id
]);

return $tag;
}
}
24 changes: 24 additions & 0 deletions app/Services/TagService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Services;

use App\Models\User;
use App\Models\Tag;
use App\Models\PostTag;

class TagService
{
public function saveTag(string $name, int $user_id): Tag|null
{
if (Tag::where('name', $name)->where('user_id', $user_id)->exists()) {
return null;
}

$tag = Tag::create([
'name' => $name,
'user_id' => $user_id
]);

return $tag;
}
}

0 comments on commit 081db3b

Please sign in to comment.