Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

My branch #24

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 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])->orderByDesc('created_at')->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::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::where('id', $id)->firstOrFail();

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

Item::create($request->validate([
'title' => ['string'],
'active' => ['boolean']
]));
return redirect('/');
}

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

$data = $request->validate([
'title' => ['string'],
'active' => ['boolean']
]);
$product->update($data);
return redirect('/');
}

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

$ids = $request->post('products');
Item::destroy($ids);
return redirect('/');
}
}
1 change: 1 addition & 0 deletions app/Http/Controllers/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,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']
];
}
}
10 changes: 10 additions & 0 deletions app/Models/Item.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

Expand All @@ -12,4 +13,13 @@ class Item extends Model
protected $fillable = ['title', 'active'];

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

/**
* Scope a query to only include users of a given type.
*/
public function scopeActive(Builder $query):void
{
$query->where('active',1);
}
}
5 changes: 3 additions & 2 deletions app/Policies/ItemPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ public function view(User $user, Item $item)
public function create(User $user)
{
// TODO Auth Задание: Разрешить добавление продуктов только пользователю с id = 10

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

/**
Expand Down
2 changes: 1 addition & 1 deletion app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ public function register()
*/
public function boot()
{

Blade::component(HelloWorld::class,'hello');
}
}
2 changes: 1 addition & 1 deletion app/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function boot()
$this->configureRateLimiting();

$this->routes(function () {
Route::prefix('api')
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Expand Down
29 changes: 29 additions & 0 deletions app/View/Components/HelloWorld.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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');
}
}

33 changes: 31 additions & 2 deletions database/migrations/tasks/2021_11_18_122318_create_posts_table.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,18 @@ 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 @@ -30,15 +39,31 @@ public function up()

Schema::table('posts', function (Blueprint $table) {
//TODO Migrations Задание 6: Добавить поле description типа text (DEFAULT NULL) ПОСЛЕ поля title
$table->addColumn('text', 'description')->after('title')->default(null);
});

//TODO Migrations Задание 7: Сделать провеку на наличие поля active и в случаи успеха добавить поле main (boolean default false)
//TODO Migrations Задание 7: Сделать провеку на наличие поля active и в случаи успеха добавить поле main (boolean default false)
if (Schema::hasColumn('posts', 'active')) {
Schema::table('posts', function (Blueprint $table){
$table->addColumn('boolean','main')->default(false);
});
}
//TODO Migrations Задание 8: Переименовать поле title в name

//TODO Migrations Задание 8: Переименовать поле title в name
Schema::table('posts', function (Blueprint $table){
$table->renameColumn('title','name');
});


//TODO Migrations Задание 9: Переименовать таблицу posts в articles
Schema::rename('posts', 'articles');

//TODO Migrations Задание 10: Добавить таблицу для связи articles и categories (belongsToMany) c foreign ключами
Schema::create('article_category', function (Blueprint $table){
$table->id();
$table->foreignId('article_id');
$table->foreignId('category_id');
});
}

/**
Expand All @@ -49,5 +74,9 @@ public function up()
public function down()
{
// TODO Migrations Задание 11: Удалить таблицы categories, articles, article_category если такие существуют
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('categories');
Schema::dropIfExists('articles');
Schema::dropIfExists('article_category');
}
}
7 changes: 6 additions & 1 deletion resources/views/auth.blade.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
<!-- TODO Blade Задание 4: Сделать проверку авторизован пользователь или нет -->
@if (\Illuminate\Support\Facades\Auth::check())
{{auth()->id()}}
@else

@endif
<!-- Если да то вывести ID пользователя -->
<!-- ID пользователя вывести внутри конструкции с проверкой -->
<!-- ID пользователя вывести внутри конструкции с проверкой -->
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>
{{now()}}
</div>
2 changes: 1 addition & 1 deletion resources/views/layouts/app.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<body class="antialiased">
<!-- TODO Blade Задание 3: Подключите view с меню -->
<!-- shared/menu.blade.php -->

@include('shared/menu')
@yield('content')
</body>
</html>
11 changes: 9 additions & 2 deletions resources/views/table.blade.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
<!-- 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 для состояния когда нет элементов в колекции -->


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

@foreach($data as $user)
@if ($loop->odd)
<div class="bg-red-500">{{$user->name}}</div>
@else
<div>{{$user->name}}</div>
@endif
@endforeach
1 change: 1 addition & 0 deletions resources/views/welcome.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<!-- и изменить его alias на hello -->
<!-- В итоге alias - hello а класс компонента App\View\Components\HelloWorld -->
<!-- и вывести его здесь -->
<x-hello></x-hello>
</div>
</body>
</html>
1 change: 1 addition & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
});

Route::group(['middleware' => 'auth:sanctum'], function() {
Route::apiResource('/users', \App\Http\Controllers\Api\V1\UserController::class);
// TODO Route Задача 13: Добавить apiResource контроллер - Api/V1/UserController.
// Префикс урла должен быть /api/v1
// Полный урл /api/v1/users (не забывайте что это api routes)
Expand Down
32 changes: 20 additions & 12 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,57 @@

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

//TODO Route Задание 2: По GET урлу / обратиться к IndexController, метод index
// Одна строка кода
Route::get('/', [\App\Http\Controllers\IndexController::class, 'index']);

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


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

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

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

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


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

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

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

Route::resource('users_crud', \App\Http\Controllers\UserCrudController::class);


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

// Задачи внутри группы роутов dashboard
//TODO Route Задание 9: Добавить роут GET /admin -> Admin/IndexController -> index
Route::controller(\App\Http\Controllers\Admin\IndexController::class)->prefix('/dashboard')->group(function (){
Route::get('/admin', 'index');
Route::post('/admin/post', 'post');
});
// Задачи внутри группы роутов dashboard
//TODO Route Задание 9: Добавить роут GET /admin -> Admin/IndexController -> index


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


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

// Задачи внутри группы роутов security
//TODO Задание 12: Добавить роут GET /admin/auth -> Admin/IndexController -> auth
Route::middleware('auth')->group(function (){
Route::get('/admin/auth',[\App\Http\Controllers\Admin\IndexController::class, 'auth'])->prefix('security');
});
// Задачи внутри группы роутов security
//TODO Задание 12: Добавить роут GET /admin/auth -> Admin/IndexController -> auth



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