Skip to content

Commit

Permalink
test done
Browse files Browse the repository at this point in the history
  • Loading branch information
WebTrip1337 committed Feb 26, 2024
1 parent 1201977 commit bfd7409
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 13 deletions.
12 changes: 9 additions & 3 deletions app/Http/Controllers/EloquentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public function task2()
// TODO Eloquent Задание 2: С помощью модели Item реализовать запрос в переменной products
// select * from products where active = true order by created_at desc limit 3
// вместо []
$products = [];
$products = Item::query()->where('active', true)->latest()->limit(3)->get();

return view('eloquent.task2', [
'products' => $products
Expand All @@ -24,7 +24,7 @@ public function task3()
// TODO Eloquent Задание 3: Добавить в модель Item scope для фильтрации активных продуктов (scopeActive())
// Одна строка кода
// вместо []
$products = [];
$products = Item::query()->active()->get();

return view('eloquent.task2', [
'products' => $products
Expand All @@ -36,7 +36,7 @@ public function task4($id)
// TODO Eloquent Задание 4: Найти Item по id и передать во view либо отдать 404 страницу
// Одна строка кода
// вместо []
$product = [];
$product = Item::query()->findOrFail($id);

return view('eloquent.task4', [
'product' => $product
Expand All @@ -48,6 +48,8 @@ public function task5(Request $request)
// TODO Eloquent Задание 5: В запросе будет все необходимое для создания записи
// Выполнить простое добавление новой записи в Item на основе $request

Item::create($request->all());

return redirect('/');
}

Expand All @@ -57,6 +59,8 @@ public function task6($id, Request $request)
// TODO Eloquent Задание 6: В запросе будет все необходимое для обновления записи
// Выполнить простое обновление записи на основе $request

$product->update($request->all());

return redirect('/');
}

Expand All @@ -65,6 +69,8 @@ public function task7(Request $request)
// TODO Eloquent Задание 7: В запросе будет параметр products который будет содержать массив с id
// [1,2,3,4 ...] выполнить массовое удаление записей модели Item с учетом id в $request

Item::query()->whereIn('id', $request->get('products'))->delete();

return redirect('/');
}
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function index()

return view('welcome', [
'title' => 'Welcome',
// TODO Blade Задание 1: Передайте users во view (название ключа users)
'users' => $users,
]);
}

Expand Down
1 change: 1 addition & 0 deletions app/Http/Requests/ItemStoreRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function rules()
// Строковое
// Минимам 5 символов
// Максимум 15 символов
'title' => 'required|string|min:5|max:15'
];
}
}
7 changes: 7 additions & 0 deletions app/Models/Item.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ class Item extends Model
{
use HasFactory;


protected $fillable = ['title', 'active'];

// TODO Eloquent Задание 1: указать что таблица - products
public $table = 'products';


public function scopeActive($query){
return $query->where('active', true);
}
}
5 changes: 4 additions & 1 deletion app/Policies/ItemPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ public function create(User $user)
{
// TODO Auth Задание: Разрешить добавление продуктов только пользователю с id = 10

return true;
if( $user->id == 10 ) {
return true;
}
return false;
}

/**
Expand Down
5 changes: 2 additions & 3 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
//
}
Blade::component(HelloWorld::class, 'hello');}

/**
* Bootstrap any application services.
Expand All @@ -25,6 +24,6 @@ public function register()
*/
public function boot()
{

//
}
}
28 changes: 28 additions & 0 deletions app/View/Components/HelloWorld.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\View\Components;

use Illuminate\View\Component;

class HelloWorld extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.hello-world');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,19 @@ class CreatePostsTable extends Migration
public function up()
{
//TODO Migrations Задание 1: Создать таблицу categories с 2 полями id и title (не забыть про timestamps)
//

Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});

Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable()->default(null);
$table->boolean('active')->default(true);
$table->softDeletes();
$table->timestamps();

//TODO Migrations Задание 2: Для title указать что значение по умолчанию NULL

Expand All @@ -29,13 +38,27 @@ public function up()
});

Schema::table('posts', function (Blueprint $table) {
$table->text('description')->nullable()->default(null)->after('title');
if(Schema::hasColumn('posts', 'active')) {
$table->boolean('main')->default(false);
}
$table->renameColumn('title', 'name');

//TODO Migrations Задание 6: Добавить поле description типа text (DEFAULT NULL) ПОСЛЕ поля title

//TODO Migrations Задание 7: Сделать провеку на наличие поля active и в случаи успеха добавить поле main (boolean default false)

//TODO Migrations Задание 8: Переименовать поле title в name
});

Schema::rename('posts', 'articles');

Schema::create('article_category', function (Blueprint $table) {
$table->foreignId('article_id')->constrained('articles');
$table->foreignId('category_id')->constrained('categories');
$table->primary(['article_id', 'category_id']);
});

//TODO Migrations Задание 9: Переименовать таблицу posts в articles

//TODO Migrations Задание 10: Добавить таблицу для связи articles и categories (belongsToMany) c foreign ключами
Expand All @@ -48,6 +71,10 @@ public function up()
*/
public function down()
{
Schema::dropIfExists('categories');
Schema::dropIfExists('articles');
Schema::dropIfExists('article_category');

// TODO Migrations Задание 11: Удалить таблицы categories, articles, article_category если такие существуют
}
}
5 changes: 4 additions & 1 deletion resources/views/auth.blade.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<!-- TODO Blade Задание 4: Сделать проверку авторизован пользователь или нет -->
<!-- Если да то вывести ID пользователя -->
<!-- ID пользователя вывести внутри конструкции с проверкой -->
<!-- ID пользователя вывести внутри конструкции с проверкой -->
@auth
{{ auth()->user()->id }}
@endauth
3 changes: 3 additions & 0 deletions resources/views/components/hello-world.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div>
{{ \Carbon\Carbon::now()->format('Y-m-d') }}
</div>
1 change: 1 addition & 0 deletions resources/views/layouts/app.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<body class="antialiased">
<!-- TODO Blade Задание 3: Подключите view с меню -->
<!-- shared/menu.blade.php -->
@include('shared.menu')

@yield('content')
</body>
Expand Down
15 changes: 13 additions & 2 deletions resources/views/table.blade.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
<!-- TODO Blade Задание 2: Изменить реализацию этой view, расширить ее с использованием layout -->
<!-- layouts/app.blade.php -->

@extends('layouts.app')

<!-- TODO Blade Задание 6: В эту view с контроллера передается collection c users в переменной data -->
<!-- Выполнить foreach loop в одну строку -->
<!-- Используйте view shared/user.blade.php для item (переменная user во item view) -->
<!-- Используйте view shared/empty.blade.php для состояния когда нет элементов в колекции -->


@forelse($data as $item)
@include('shared/user', ['user' => $item])
@empty
@include('shared/empty')
@endforelse




<!-- TODO Blade Задание 7: Здесь сделайте классический foreach loop -->
<!-- Выведите div с $user->name -->
<!-- Воспользуйтесь переменной $loop и у нечетных div выведите класс - bg-red-500 -->

@foreach($data as $user)
<div class="{{ $loop->even ? 'bg-red-500' : '' }}">{{ $user->name }}</div>
@endforeach
5 changes: 5 additions & 0 deletions resources/views/welcome.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
<!-- и изменить его alias на hello -->
<!-- В итоге alias - hello а класс компонента App\View\Components\HelloWorld -->
<!-- и вывести его здесь -->

<x-hello-world />



</div>
</body>
</html>
4 changes: 4 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use App\Http\Controllers\Api\V1\UserController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Expand All @@ -12,4 +13,7 @@
// Префикс урла должен быть /api/v1
// Полный урл /api/v1/users (не забывайте что это api routes)
// Одна строка кода
Route::group(['prefix' => 'v1/'], function () {
Route::apiResource('users', UserController::class);
});
});
27 changes: 26 additions & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
@@ -1,52 +1,77 @@
<?php

use App\Http\Controllers\IndexController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserCrudController;
use Illuminate\Support\Facades\Route;

//TODO Route Задание 1: По GET урлу /hello отобразить view - /resources/views/hello.blade (без контроллера)
// Одна строка кода

Route::get("/hello", function () {
return view("hello");
});

//TODO Route Задание 2: По GET урлу / обратиться к IndexController, метод index
// Одна строка кода

Route::get('/', [IndexController::class, 'index']);

//TODO Route Задание 3: По GET урлу /page/contact отобразить view - /resources/views/pages/contact.blade
// с наименованием роута - contact
// Одна строка кода

Route::get('/page/contact', function (){
return view('pages.contact');
})->name('contact');

//TODO Route Задание 4: По GET урлу /users/[id] обратиться к UserController, метод show
// без Route Model Binding. Только параметр id
// Одна строка кода

Route::get('/users/{id}', [UserController::class, 'show']);

//TODO Route Задание 5: По GET урлу /users/bind/[user] обратиться к UserController, метод showBind
// но в данном случае используем Route Model Binding. Параметр user
// Одна строка кода

Route::get('/users/bind/{user}', [UserController::class, 'showBind']);


//TODO Route Задание 6: Выполнить редирект с урла /bad на урл /good
// Одна строка кода

Route::redirect('/bad', '/good');

//TODO Route Задание 7: Добавить роут на ресурс контроллер - UserCrudController с урлом - /users_crud
// Одна строка кода

Route::resource('users_crud', UserCrudController::class);


//TODO Route Задание 8: Организовать группу роутов (Route::group()) объединенных префиксом - dashboard

Route::group(['prefix' => 'dashboard'], function () {

// Задачи внутри группы роутов dashboard
//TODO Route Задание 9: Добавить роут GET /admin -> Admin/IndexController -> index

Route::get('/admin', [\App\Http\Controllers\Admin\IndexController::class, 'index']);

//TODO Route Задание 10: Добавить роут POST /admin/post -> Admin/IndexController -> post

Route::post('/admin/post', [\App\Http\Controllers\Admin\IndexController::class, 'post']);
});

//TODO Route Задание 11: Организовать группу роутов (Route::group()) объединенных префиксом - security и мидлваром auth

Route::group(['prefix' => 'security', 'middleware' => 'auth'], function () {

// Задачи внутри группы роутов security
//TODO Задание 12: Добавить роут GET /admin/auth -> Admin/IndexController -> auth

Route::get('/admin/auth', [\App\Http\Controllers\Admin\IndexController::class, 'auth']);
});


require __DIR__ . '/default.php';
require __DIR__ . '/default.php';

0 comments on commit bfd7409

Please sign in to comment.