├── public
├── favicon.ico
├── robots.txt
├── .htaccess
├── web.config
└── index.php
├── resources
├── css
│ └── app.css
├── js
│ ├── app.js
│ └── bootstrap.js
├── lang
│ └── en
│ │ ├── pagination.php
│ │ ├── auth.php
│ │ ├── passwords.php
│ │ └── validation.php
└── views
│ └── welcome.blade.php
├── database
├── .gitignore
├── factories
│ ├── ImageFactory.php
│ ├── TagFactory.php
│ ├── ReservationFactory.php
│ ├── UserFactory.php
│ └── OfficeFactory.php
├── migrations
│ ├── 2021_09_09_124252_create_images_table.php
│ ├── 2014_10_12_100000_create_password_resets_table.php
│ ├── 2021_09_09_124230_create_tags_table.php
│ ├── 2019_08_19_000000_create_failed_jobs_table.php
│ ├── 2014_10_12_000000_create_users_table.php
│ ├── 2019_12_14_000001_create_personal_access_tokens_table.php
│ ├── 2021_09_09_124300_create_reservations_table.php
│ └── 2021_09_09_124245_create_offices_table.php
└── seeders
│ └── DatabaseSeeder.php
├── bootstrap
├── cache
│ └── .gitignore
└── app.php
├── storage
├── logs
│ └── .gitignore
├── app
│ ├── public
│ │ └── .gitignore
│ └── .gitignore
└── framework
│ ├── testing
│ └── .gitignore
│ ├── views
│ └── .gitignore
│ ├── cache
│ ├── data
│ │ └── .gitignore
│ └── .gitignore
│ ├── sessions
│ └── .gitignore
│ └── .gitignore
├── .gitattributes
├── .styleci.yml
├── .gitignore
├── .editorconfig
├── app
├── Http
│ ├── Controllers
│ │ ├── UserController.php
│ │ ├── TagController.php
│ │ ├── Controller.php
│ │ ├── LogoutController.php
│ │ ├── LoginController.php
│ │ ├── RegisterController.php
│ │ ├── OfficeImageController.php
│ │ ├── HostReservationController.php
│ │ ├── OfficeController.php
│ │ └── UserReservationController.php
│ ├── Middleware
│ │ ├── EncryptCookies.php
│ │ ├── VerifyCsrfToken.php
│ │ ├── TrustHosts.php
│ │ ├── PreventRequestsDuringMaintenance.php
│ │ ├── TrimStrings.php
│ │ ├── Authenticate.php
│ │ ├── TrustProxies.php
│ │ └── RedirectIfAuthenticated.php
│ ├── Resources
│ │ ├── TagResource.php
│ │ ├── ImageResource.php
│ │ ├── UserResource.php
│ │ ├── ReservationResource.php
│ │ └── OfficeResource.php
│ └── Kernel.php
├── Models
│ ├── Image.php
│ ├── Tag.php
│ ├── User.php
│ ├── Validators
│ │ └── OfficeValidator.php
│ ├── Reservation.php
│ └── Office.php
├── Providers
│ ├── BroadcastServiceProvider.php
│ ├── AuthServiceProvider.php
│ ├── EventServiceProvider.php
│ ├── AppServiceProvider.php
│ └── RouteServiceProvider.php
├── Policies
│ └── OfficePolicy.php
├── Exceptions
│ └── Handler.php
├── Console
│ ├── Kernel.php
│ └── Commands
│ │ └── SendDueReservationsNotifications.php
└── Notifications
│ ├── OfficePendingApproval.php
│ ├── NewHostReservation.php
│ ├── NewUserReservation.php
│ ├── HostReservationStarting.php
│ └── UserReservationStarting.php
├── config
├── cors.php
├── services.php
├── view.php
├── hashing.php
├── sanctum.php
├── broadcasting.php
├── filesystems.php
├── queue.php
├── logging.php
├── cache.php
├── mail.php
├── auth.php
├── database.php
├── session.php
└── app.php
├── tests
├── CreatesApplication.php
├── TestCase.php
└── Feature
│ ├── TagsControllerTest.php
│ ├── OfficeImageControllerTest.php
│ ├── UserReservationControllerTest.php
│ └── OfficeControllerTest.php
├── package.json
├── routes
├── web.php
├── channels.php
├── console.php
└── api.php
├── webpack.mix.js
├── server.php
├── TODO.md
├── .env.example
├── phpunit.xml
├── artisan
├── README.md
└── composer.json
/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/resources/css/app.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/database/.gitignore:
--------------------------------------------------------------------------------
1 | *.sqlite*
2 |
--------------------------------------------------------------------------------
/bootstrap/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/resources/js/app.js:
--------------------------------------------------------------------------------
1 | require('./bootstrap');
2 |
--------------------------------------------------------------------------------
/storage/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
3 |
--------------------------------------------------------------------------------
/storage/app/public/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/app/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !public/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/storage/framework/testing/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/views/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/cache/data/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/sessions/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !data/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.css linguist-vendored
3 | *.scss linguist-vendored
4 | *.js linguist-vendored
5 | CHANGELOG.md export-ignore
6 |
--------------------------------------------------------------------------------
/storage/framework/.gitignore:
--------------------------------------------------------------------------------
1 | compiled.php
2 | config.php
3 | down
4 | events.scanned.php
5 | maintenance.php
6 | routes.php
7 | routes.scanned.php
8 | schedule-*
9 | services.json
10 |
--------------------------------------------------------------------------------
/.styleci.yml:
--------------------------------------------------------------------------------
1 | php:
2 | preset: laravel
3 | version: 8
4 | disabled:
5 | - no_unused_imports
6 | finder:
7 | not-name:
8 | - index.php
9 | - server.php
10 | js:
11 | finder:
12 | not-name:
13 | - webpack.mix.js
14 | css: true
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /public/hot
3 | /public/storage
4 | /storage/*.key
5 | /vendor
6 | .env
7 | .env.backup
8 | .phpunit.result.cache
9 | docker-compose.override.yml
10 | Homestead.json
11 | Homestead.yaml
12 | npm-debug.log
13 | yarn-error.log
14 | /.idea
15 | /.vscode
16 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | indent_style = space
8 | indent_size = 4
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
14 | [*.{yml,yaml}]
15 | indent_size = 2
16 |
17 | [docker-compose.yml]
18 | indent_size = 4
19 |
--------------------------------------------------------------------------------
/app/Http/Controllers/UserController.php:
--------------------------------------------------------------------------------
1 | user()
14 | );
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/config/cors.php:
--------------------------------------------------------------------------------
1 | ['*'],
6 |
7 | 'allowed_methods' => ['*'],
8 |
9 | 'allowed_origins' => ['*'],
10 |
11 | 'allowed_origins_patterns' => [],
12 |
13 | 'allowed_headers' => ['*'],
14 |
15 | 'exposed_headers' => [],
16 |
17 | 'max_age' => 0,
18 |
19 | 'supports_credentials' => true,
20 |
21 | ];
22 |
--------------------------------------------------------------------------------
/app/Http/Controllers/TagController.php:
--------------------------------------------------------------------------------
1 | morphTo();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/Http/Middleware/VerifyCsrfToken.php:
--------------------------------------------------------------------------------
1 | belongsToMany(Office::class, 'offices_tags');
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/Http/Middleware/TrustHosts.php:
--------------------------------------------------------------------------------
1 | allSubdomainsOfApplicationUrl(),
18 | ];
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/Http/Middleware/PreventRequestsDuringMaintenance.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class)->bootstrap();
19 |
20 | return $app;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tests/TestCase.php:
--------------------------------------------------------------------------------
1 | id == $office->user_id;
16 | }
17 |
18 | public function delete(User $user, Office $office)
19 | {
20 | return $user->id == $office->user_id;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/Http/Resources/TagResource.php:
--------------------------------------------------------------------------------
1 | expectsJson()) {
18 | return route('login');
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/database/factories/ImageFactory.php:
--------------------------------------------------------------------------------
1 | 'image.png'
26 | ];
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/database/factories/TagFactory.php:
--------------------------------------------------------------------------------
1 | $this->faker->word,
26 | ];
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/resources/lang/en/pagination.php:
--------------------------------------------------------------------------------
1 | '« Previous',
17 | 'next' => 'Next »',
18 |
19 | ];
20 |
--------------------------------------------------------------------------------
/webpack.mix.js:
--------------------------------------------------------------------------------
1 | const mix = require('laravel-mix');
2 |
3 | /*
4 | |--------------------------------------------------------------------------
5 | | Mix Asset Management
6 | |--------------------------------------------------------------------------
7 | |
8 | | Mix provides a clean, fluent API for defining some Webpack build steps
9 | | for your Laravel applications. By default, we are compiling the CSS
10 | | file for the application as well as bundling up all the JS files.
11 | |
12 | */
13 |
14 | mix.js('resources/js/app.js', 'public/js')
15 | .postCss('resources/css/app.css', 'public/css', [
16 | //
17 | ]);
18 |
--------------------------------------------------------------------------------
/routes/channels.php:
--------------------------------------------------------------------------------
1 | id === (int) $id;
18 | });
19 |
--------------------------------------------------------------------------------
/tests/Feature/TagsControllerTest.php:
--------------------------------------------------------------------------------
1 | get('/tags');
20 |
21 | $response->assertStatus(200);
22 |
23 | $this->assertNotNull($response->json('data')[0]['id']);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/server.php:
--------------------------------------------------------------------------------
1 |
8 | */
9 |
10 | $uri = urldecode(
11 | parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
12 | );
13 |
14 | // This file allows us to emulate Apache's "mod_rewrite" functionality from the
15 | // built-in PHP web server. This provides a convenient way to test a Laravel
16 | // application without having installed a "real" web server software here.
17 | if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
18 | return false;
19 | }
20 |
21 | require_once __DIR__.'/public/index.php';
22 |
--------------------------------------------------------------------------------
/app/Http/Resources/ImageResource.php:
--------------------------------------------------------------------------------
1 | Storage::url($this->path),
20 |
21 | $this->merge(parent::toArray($request))
22 | ];
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/routes/console.php:
--------------------------------------------------------------------------------
1 | comment(Inspiring::quote());
19 | })->purpose('Display an inspiring quote');
20 |
--------------------------------------------------------------------------------
/public/.htaccess:
--------------------------------------------------------------------------------
1 |
2 |
3 | Options -MultiViews -Indexes
4 |
5 |
6 | RewriteEngine On
7 |
8 | # Handle Authorization Header
9 | RewriteCond %{HTTP:Authorization} .
10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
11 |
12 | # Redirect Trailing Slashes If Not A Folder...
13 | RewriteCond %{REQUEST_FILENAME} !-d
14 | RewriteCond %{REQUEST_URI} (.+)/$
15 | RewriteRule ^ %1 [L,R=301]
16 |
17 | # Send Requests To Front Controller...
18 | RewriteCond %{REQUEST_FILENAME} !-d
19 | RewriteCond %{REQUEST_FILENAME} !-f
20 | RewriteRule ^ index.php [L]
21 |
22 |
--------------------------------------------------------------------------------
/app/Http/Resources/UserResource.php:
--------------------------------------------------------------------------------
1 | merge(Arr::except(parent::toArray($request), [
20 | 'created_at', 'updated_at', 'email', 'email_verified_at'
21 | ]))
22 | ];
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/Providers/AuthServiceProvider.php:
--------------------------------------------------------------------------------
1 | 'App\Policies\ModelPolicy',
17 | ];
18 |
19 | /**
20 | * Register any authentication / authorization services.
21 | *
22 | * @return void
23 | */
24 | public function boot()
25 | {
26 | $this->registerPolicies();
27 |
28 | //
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/Http/Resources/ReservationResource.php:
--------------------------------------------------------------------------------
1 | OfficeResource::make($this->whenLoaded('office')),
20 |
21 | $this->merge(Arr::except(parent::toArray($request), [
22 |
23 | ]))
24 | ];
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/resources/lang/en/auth.php:
--------------------------------------------------------------------------------
1 | 'These credentials do not match our records.',
17 | 'password' => 'The provided password is incorrect.',
18 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
19 |
20 | ];
21 |
--------------------------------------------------------------------------------
/app/Http/Middleware/TrustProxies.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->morphs('resource');
19 | $table->string('path');
20 | $table->timestamps();
21 | });
22 | }
23 |
24 | /**
25 | * Reverse the migrations.
26 | *
27 | * @return void
28 | */
29 | public function down()
30 | {
31 | Schema::dropIfExists('images');
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/Providers/EventServiceProvider.php:
--------------------------------------------------------------------------------
1 | [
19 | SendEmailVerificationNotification::class,
20 | ],
21 | ];
22 |
23 | /**
24 | * Register any events for your application.
25 | *
26 | * @return void
27 | */
28 | public function boot()
29 | {
30 | //
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/resources/lang/en/passwords.php:
--------------------------------------------------------------------------------
1 | 'Your password has been reset!',
17 | 'sent' => 'We have emailed your password reset link!',
18 | 'throttled' => 'Please wait before retrying.',
19 | 'token' => 'This password reset token is invalid.',
20 | 'user' => "We can't find a user with that email address.",
21 |
22 | ];
23 |
--------------------------------------------------------------------------------
/database/migrations/2014_10_12_100000_create_password_resets_table.php:
--------------------------------------------------------------------------------
1 | string('email')->index();
18 | $table->string('token');
19 | $table->timestamp('created_at')->nullable();
20 | });
21 | }
22 |
23 | /**
24 | * Reverse the migrations.
25 | *
26 | * @return void
27 | */
28 | public function down()
29 | {
30 | Schema::dropIfExists('password_resets');
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/Http/Middleware/RedirectIfAuthenticated.php:
--------------------------------------------------------------------------------
1 | check()) {
26 | return redirect(RouteServiceProvider::HOME);
27 | }
28 | }
29 |
30 | return $next($request);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/Providers/AppServiceProvider.php:
--------------------------------------------------------------------------------
1 | Office::class,
35 | 'user' => User::class
36 | ]);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/TODO.md:
--------------------------------------------------------------------------------
1 | # TODO
2 |
3 | ## Make Reservations Endpoint
4 |
5 | [x] Read request input from the validator output
6 | [x] You cannot make a reservation on a pending or a hidden office
7 | [x] Test you can make a reservation starting next day but cannot make one on same day
8 | [x] Email user & host when a reservation is made
9 | [x] Email user & host on reservation start day
10 | [x] Generate WIFI password for new reservations (store encrypted)
11 |
12 | ## Cancel Reservation Endpoint
13 |
14 | [x] Must be authenticated & email verified
15 | [x] Token (if exists) must allow `reservations.cancel`
16 | [x] Can only cancel their own reservation
17 | [x] Can only cancel an active reservation that has a start_date in the future
18 |
19 | ## Housekeeping
20 |
21 | [x] Filter offices by tag
22 | [x] API should return the full URI of the image so that the consumer can load it easily
23 | [] Test SendDueReservationsNotifications command
24 |
25 |
--------------------------------------------------------------------------------
/database/migrations/2021_09_09_124230_create_tags_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('name');
19 | });
20 |
21 | \App\Models\Tag::create(['name' => 'has_ac']);
22 | \App\Models\Tag::create(['name' => 'has_private_bathroom']);
23 | \App\Models\Tag::create(['name' => 'has_coffee_machine']);
24 | }
25 |
26 | /**
27 | * Reverse the migrations.
28 | *
29 | * @return void
30 | */
31 | public function down()
32 | {
33 | Schema::dropIfExists('tags');
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/app/Exceptions/Handler.php:
--------------------------------------------------------------------------------
1 | reportable(function (Throwable $e) {
38 | //
39 | });
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/resources/js/bootstrap.js:
--------------------------------------------------------------------------------
1 | window._ = require('lodash');
2 |
3 | /**
4 | * We'll load the axios HTTP library which allows us to easily issue requests
5 | * to our Laravel back-end. This library automatically handles sending the
6 | * CSRF token as a header based on the value of the "XSRF" token cookie.
7 | */
8 |
9 | window.axios = require('axios');
10 |
11 | window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
12 |
13 | /**
14 | * Echo exposes an expressive API for subscribing to channels and listening
15 | * for events that are broadcast by Laravel. Echo and event broadcasting
16 | * allows your team to easily build robust real-time web applications.
17 | */
18 |
19 | // import Echo from 'laravel-echo';
20 |
21 | // window.Pusher = require('pusher-js');
22 |
23 | // window.Echo = new Echo({
24 | // broadcaster: 'pusher',
25 | // key: process.env.MIX_PUSHER_APP_KEY,
26 | // cluster: process.env.MIX_PUSHER_APP_CLUSTER,
27 | // forceTLS: true
28 | // });
29 |
--------------------------------------------------------------------------------
/database/migrations/2019_08_19_000000_create_failed_jobs_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('uuid')->unique();
19 | $table->text('connection');
20 | $table->text('queue');
21 | $table->longText('payload');
22 | $table->longText('exception');
23 | $table->timestamp('failed_at')->useCurrent();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::dropIfExists('failed_jobs');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/database/migrations/2014_10_12_000000_create_users_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('name');
19 | $table->string('email')->unique();
20 | $table->timestamp('email_verified_at')->nullable();
21 | $table->string('password');
22 | $table->boolean('is_admin')->default(false);
23 | $table->rememberToken();
24 | $table->timestamps();
25 | });
26 | }
27 |
28 | /**
29 | * Reverse the migrations.
30 | *
31 | * @return void
32 | */
33 | public function down()
34 | {
35 | Schema::dropIfExists('users');
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | APP_NAME=Laravel
2 | APP_ENV=local
3 | APP_KEY=
4 | APP_DEBUG=true
5 | APP_URL=http://localhost
6 |
7 | LOG_CHANNEL=stack
8 | LOG_LEVEL=debug
9 |
10 | DB_CONNECTION=mysql
11 | DB_HOST=127.0.0.1
12 | DB_PORT=3306
13 | DB_DATABASE=ergodnc
14 | DB_USERNAME=root
15 | DB_PASSWORD=
16 |
17 | BROADCAST_DRIVER=log
18 | CACHE_DRIVER=file
19 | FILESYSTEM_DRIVER=local
20 | QUEUE_CONNECTION=sync
21 | SESSION_DRIVER=file
22 | SESSION_LIFETIME=120
23 |
24 | MEMCACHED_HOST=127.0.0.1
25 |
26 | REDIS_HOST=127.0.0.1
27 | REDIS_PASSWORD=null
28 | REDIS_PORT=6379
29 |
30 | MAIL_MAILER=smtp
31 | MAIL_HOST=mailhog
32 | MAIL_PORT=1025
33 | MAIL_USERNAME=null
34 | MAIL_PASSWORD=null
35 | MAIL_ENCRYPTION=null
36 | MAIL_FROM_ADDRESS=null
37 | MAIL_FROM_NAME="${APP_NAME}"
38 |
39 | AWS_ACCESS_KEY_ID=
40 | AWS_SECRET_ACCESS_KEY=
41 | AWS_DEFAULT_REGION=us-east-1
42 | AWS_BUCKET=
43 | AWS_USE_PATH_STYLE_ENDPOINT=false
44 |
45 | PUSHER_APP_ID=
46 | PUSHER_APP_KEY=
47 | PUSHER_APP_SECRET=
48 | PUSHER_APP_CLUSTER=mt1
49 |
50 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
51 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
52 |
--------------------------------------------------------------------------------
/config/services.php:
--------------------------------------------------------------------------------
1 | [
18 | 'domain' => env('MAILGUN_DOMAIN'),
19 | 'secret' => env('MAILGUN_SECRET'),
20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
21 | ],
22 |
23 | 'postmark' => [
24 | 'token' => env('POSTMARK_TOKEN'),
25 | ],
26 |
27 | 'ses' => [
28 | 'key' => env('AWS_ACCESS_KEY_ID'),
29 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
30 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
31 | ],
32 |
33 | ];
34 |
--------------------------------------------------------------------------------
/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php:
--------------------------------------------------------------------------------
1 | bigIncrements('id');
18 | $table->morphs('tokenable');
19 | $table->string('name');
20 | $table->string('token', 64)->unique();
21 | $table->text('abilities')->nullable();
22 | $table->timestamp('last_used_at')->nullable();
23 | $table->timestamps();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::dropIfExists('personal_access_tokens');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/app/Http/Resources/OfficeResource.php:
--------------------------------------------------------------------------------
1 | UserResource::make($this->whenLoaded('user')),
20 | 'images' => ImageResource::collection($this->whenLoaded('images')),
21 | 'tags' => TagResource::collection($this->whenLoaded('tags')),
22 | 'featured_image' => ImageResource::make($this->whenLoaded('featuredImage')),
23 | 'reservations_count' => $this->resource->reservations_count ?? 0,
24 |
25 | $this->merge(Arr::except(parent::toArray($request), [
26 | 'user_id', 'created_at', 'updated_at',
27 | 'deleted_at'
28 | ]))
29 | ];
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/Console/Kernel.php:
--------------------------------------------------------------------------------
1 | command('inspire')->hourly();
29 |
30 | $schedule->command(SendDueReservationsNotifications::class)->dailyAt('00:00');
31 | }
32 |
33 | /**
34 | * Register the commands for the application.
35 | *
36 | * @return void
37 | */
38 | protected function commands()
39 | {
40 | $this->load(__DIR__.'/Commands');
41 |
42 | require base_path('routes/console.php');
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | ./tests/Feature
10 |
11 |
12 |
13 |
14 | ./app
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/database/factories/ReservationFactory.php:
--------------------------------------------------------------------------------
1 | User::factory(),
28 | 'office_id' => Office::factory(),
29 | 'price' => $this->faker->numberBetween(10_000, 20_000),
30 | 'status' => Reservation::STATUS_ACTIVE,
31 | 'start_date' => now()->addDay()->format('Y-m-d'),
32 | 'end_date' => now()->addDays(5)->format('Y-m-d'),
33 | ];
34 | }
35 |
36 | public function cancelled(): Factory
37 | {
38 | return $this->state([
39 | 'status' => Reservation::STATUS_CANCELLED,
40 | ]);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/config/view.php:
--------------------------------------------------------------------------------
1 | [
17 | resource_path('views'),
18 | ],
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Compiled View Path
23 | |--------------------------------------------------------------------------
24 | |
25 | | This option determines where all the compiled Blade templates will be
26 | | stored for your application. Typically, this is within the storage
27 | | directory. However, as usual, you are free to change this value.
28 | |
29 | */
30 |
31 | 'compiled' => env(
32 | 'VIEW_COMPILED_PATH',
33 | realpath(storage_path('framework/views'))
34 | ),
35 |
36 | ];
37 |
--------------------------------------------------------------------------------
/app/Http/Controllers/LogoutController.php:
--------------------------------------------------------------------------------
1 | logout();
29 |
30 | request()->session()->invalidate();
31 |
32 | request()->session()->regenerateToken();
33 | } else {
34 | // Revoke token
35 | }
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/Models/User.php:
--------------------------------------------------------------------------------
1 | 'datetime',
43 | 'is_admin' => 'boolean'
44 | ];
45 |
46 | public function offices(): \Illuminate\Database\Eloquent\Relations\HasMany
47 | {
48 | return $this->hasMany(Office::class);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/public/web.config:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/database/factories/UserFactory.php:
--------------------------------------------------------------------------------
1 | $this->faker->name(),
27 | 'email' => $this->faker->unique()->safeEmail(),
28 | 'email_verified_at' => now(),
29 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
30 | 'remember_token' => Str::random(10),
31 | ];
32 | }
33 |
34 | /**
35 | * Indicate that the model's email address should be unverified.
36 | *
37 | * @return Factory
38 | */
39 | public function unverified(): Factory
40 | {
41 | return $this->state(function (array $attributes) {
42 | return [
43 | 'email_verified_at' => null,
44 | ];
45 | });
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/database/migrations/2021_09_09_124300_create_reservations_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->foreignId('user_id');
19 | $table->foreignId('office_id');
20 | $table->integer('price');
21 | $table->tinyInteger('status')->default(1);
22 | $table->date('start_date');
23 | $table->date('end_date');
24 | $table->text('wifi_password')->nullable();
25 | $table->timestamps();
26 |
27 | $table->index(['user_id', 'status']);
28 | $table->index(['office_id', 'status']);
29 | $table->index(['office_id', 'status', 'start_date', 'end_date']);
30 | });
31 | }
32 |
33 | /**
34 | * Reverse the migrations.
35 | *
36 | * @return void
37 | */
38 | public function down()
39 | {
40 | Schema::dropIfExists('reservations');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/Http/Controllers/LoginController.php:
--------------------------------------------------------------------------------
1 | validate([
14 | 'email' => ['required', 'string', 'email'],
15 | 'password' => ['required'],
16 | ]);
17 |
18 | /**
19 | * We are authenticating a request from our frontend.
20 | */
21 | if (EnsureFrontendRequestsAreStateful::fromFrontend(request())) {
22 | $this->authenticateFrontend();
23 | }
24 | /**
25 | * We are authenticating a request from a 3rd party.
26 | */
27 | else {
28 | // Use token authentication.
29 | }
30 | }
31 |
32 | private function authenticateFrontend()
33 | {
34 | if (! Auth::guard('web')
35 | ->attempt(
36 | request()->only('email', 'password'),
37 | request()->boolean('remember')
38 | )) {
39 | throw ValidationException::withMessages([
40 | 'email' => __('auth.failed'),
41 | ]);
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/Models/Validators/OfficeValidator.php:
--------------------------------------------------------------------------------
1 | [Rule::when($office->exists, 'sometimes'), 'required', 'string'],
15 | 'description' => [Rule::when($office->exists, 'sometimes'), 'required', 'string'],
16 | 'lat' => [Rule::when($office->exists, 'sometimes'), 'required', 'numeric'],
17 | 'lng' => [Rule::when($office->exists, 'sometimes'), 'required', 'numeric'],
18 | 'address_line1' => [Rule::when($office->exists, 'sometimes'), 'required', 'string'],
19 | 'address_line2' => ['string'],
20 | 'price_per_day' => [Rule::when($office->exists, 'sometimes'), 'required', 'integer', 'min:100'],
21 |
22 |
23 | 'featured_image_id' => [Rule::exists('images', 'id')->where('resource_type', 'office')->where('resource_id', $office->id)],
24 | 'hidden' => ['bool'],
25 | 'monthly_discount' => ['integer', 'min:0', 'max:90'],
26 |
27 | 'tags' => ['array'],
28 | 'tags.*' => ['integer', Rule::exists('tags', 'id')]
29 | ]
30 | )->validate();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/database/seeders/DatabaseSeeder.php:
--------------------------------------------------------------------------------
1 | 'Mohamed',
22 | 'email' => 'mohamed@laravel.com',
23 | 'password' => Hash::make('asdasdasd')
24 | ]);
25 |
26 | $office1 = Office::factory()->create();
27 | $office2 = Office::factory()->create();
28 | $office3 = Office::factory()->create();
29 |
30 | $office1->update([
31 | 'featured_image_id' => $office1->images()->create([
32 | 'path' => '1.jpg'
33 | ])->id
34 | ]);
35 |
36 | $office2->update([
37 | 'featured_image_id' => $office2->images()->create([
38 | 'path' => '2.jpg'
39 | ])->id
40 | ]);
41 |
42 | $office3->update([
43 | 'featured_image_id' => $office3->images()->create([
44 | 'path' => '3.jpg'
45 | ])->id
46 | ]);
47 |
48 | Reservation::factory()->for($user)->for($office3)->create();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/Http/Controllers/RegisterController.php:
--------------------------------------------------------------------------------
1 | validate([
30 | 'name' => ['required', 'string', 'max:255'],
31 | 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
32 | 'password' => ['required', 'confirmed'],
33 | ]);
34 |
35 | $user = User::create([
36 | 'name' => request('name'),
37 | 'email' => request('email'),
38 | 'password' => Hash::make(request('password')),
39 | ]);
40 |
41 | Auth::guard('web')->login($user);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/database/factories/OfficeFactory.php:
--------------------------------------------------------------------------------
1 | User::factory(),
27 | 'title' => $this->faker->city,
28 | 'description' => $this->faker->paragraph,
29 | 'lat' => $this->faker->latitude,
30 | 'lng' => $this->faker->longitude,
31 | 'address_line1' => $this->faker->address,
32 | 'approval_status' => Office::APPROVAL_APPROVED,
33 | 'hidden' => false,
34 | 'price_per_day' => $this->faker->randomElement([1_000, 2_000, 3_000, 4_000]),
35 | 'monthly_discount' => 0
36 | ];
37 | }
38 |
39 | public function pending(): Factory
40 | {
41 | return $this->state([
42 | 'approval_status' => Office::APPROVAL_PENDING,
43 | ]);
44 | }
45 |
46 | public function hidden(): Factory
47 | {
48 | return $this->state([
49 | 'hidden' => true,
50 | ]);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/Models/Reservation.php:
--------------------------------------------------------------------------------
1 | 'integer',
18 | 'status' => 'integer',
19 | 'start_date' => 'immutable_date',
20 | 'end_date' => 'immutable_date',
21 | 'wifi_password' => 'encrypted'
22 | ];
23 |
24 | public function user(): BelongsTo
25 | {
26 | return $this->belongsTo(User::class);
27 | }
28 |
29 | public function office(): BelongsTo
30 | {
31 | return $this->belongsTo(Office::class);
32 | }
33 |
34 | public function scopeActiveBetween($query, $from, $to)
35 | {
36 | $query->whereStatus(Reservation::STATUS_ACTIVE)
37 | ->betweenDates($from, $to);
38 | }
39 |
40 | public function scopeBetweenDates($query, $from, $to)
41 | {
42 | $query->where(function ($query) use ($to, $from) {
43 | $query
44 | ->whereBetween('start_date', [$from, $to])
45 | ->orWhereBetween('end_date', [$from, $to])
46 | ->orWhere(function ($query) use ($to, $from) {
47 | $query
48 | ->where('start_date', '<', $from)
49 | ->where('end_date', '>', $to);
50 | });
51 | });
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/Console/Commands/SendDueReservationsNotifications.php:
--------------------------------------------------------------------------------
1 | with('office.user')
46 | ->where('status', Reservation::STATUS_ACTIVE)
47 | ->where('start_date', now()->toDateString())
48 | ->each(function ($reservation) {
49 | Notification::send($reservation->user, new UserReservationStarting($reservation));
50 | Notification::send($reservation->office->user, new HostReservationStarting($reservation));
51 | });
52 |
53 |
54 | return 0;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/app/Notifications/OfficePendingApproval.php:
--------------------------------------------------------------------------------
1 | line('The introduction to the notification.')
46 | ->action('Notification Action', url('/'))
47 | ->line('Thank you for using our application!');
48 | }
49 |
50 | /**
51 | * Get the array representation of the notification.
52 | *
53 | * @param mixed $notifiable
54 | * @return array
55 | */
56 | public function toArray($notifiable)
57 | {
58 | return [
59 | //
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Notifications/NewHostReservation.php:
--------------------------------------------------------------------------------
1 | line('The introduction to the notification.')
46 | ->action('Notification Action', url('/'))
47 | ->line('Thank you for using our application!');
48 | }
49 |
50 | /**
51 | * Get the array representation of the notification.
52 | *
53 | * @param mixed $notifiable
54 | * @return array
55 | */
56 | public function toArray($notifiable)
57 | {
58 | return [
59 | //
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Notifications/NewUserReservation.php:
--------------------------------------------------------------------------------
1 | line('The introduction to the notification.')
46 | ->action('Notification Action', url('/'))
47 | ->line('Thank you for using our application!');
48 | }
49 |
50 | /**
51 | * Get the array representation of the notification.
52 | *
53 | * @param mixed $notifiable
54 | * @return array
55 | */
56 | public function toArray($notifiable)
57 | {
58 | return [
59 | //
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Notifications/HostReservationStarting.php:
--------------------------------------------------------------------------------
1 | line('The introduction to the notification.')
46 | ->action('Notification Action', url('/'))
47 | ->line('Thank you for using our application!');
48 | }
49 |
50 | /**
51 | * Get the array representation of the notification.
52 | *
53 | * @param mixed $notifiable
54 | * @return array
55 | */
56 | public function toArray($notifiable)
57 | {
58 | return [
59 | //
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Notifications/UserReservationStarting.php:
--------------------------------------------------------------------------------
1 | line('The introduction to the notification.')
46 | ->action('Notification Action', url('/'))
47 | ->line('Thank you for using our application!');
48 | }
49 |
50 | /**
51 | * Get the array representation of the notification.
52 | *
53 | * @param mixed $notifiable
54 | * @return array
55 | */
56 | public function toArray($notifiable)
57 | {
58 | return [
59 | //
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/database/migrations/2021_09_09_124245_create_offices_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->foreignId('user_id')->index();
19 | $table->foreignId('featured_image_id')->index()->nullable();
20 | $table->string('title');
21 | $table->text('description');
22 | $table->decimal('lat', 11, 8);
23 | $table->decimal('lng', 11, 8);
24 | $table->text('address_line1');
25 | $table->text('address_line2')->nullable();
26 | $table->tinyInteger('approval_status')->default(1);
27 | $table->boolean('hidden')->default(false);
28 | $table->integer('price_per_day');
29 | $table->integer('monthly_discount')->default(0);
30 | $table->timestamps();
31 | $table->softDeletes();
32 | });
33 |
34 | Schema::create('offices_tags', function (Blueprint $table) {
35 | $table->foreignId('office_id')->index();
36 | $table->foreignId('tag_id')->index();
37 |
38 | $table->unique(['office_id', 'tag_id']);
39 | });
40 | }
41 |
42 | /**
43 | * Reverse the migrations.
44 | *
45 | * @return void
46 | */
47 | public function down()
48 | {
49 | Schema::dropIfExists('offices');
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/Http/Controllers/OfficeImageController.php:
--------------------------------------------------------------------------------
1 | user()->tokenCan('office.update'),
19 | Response::HTTP_FORBIDDEN
20 | );
21 |
22 | $this->authorize('update', $office);
23 |
24 | request()->validate([
25 | 'image' => ['file', 'max:5000', 'mimes:jpg,png']
26 | ]);
27 |
28 | $path = request()->file('image')->storePublicly('/');
29 |
30 | $image = $office->images()->create([
31 | 'path' => $path
32 | ]);
33 |
34 | return ImageResource::make($image);
35 | }
36 |
37 | public function delete(Office $office, Image $image)
38 | {
39 | abort_unless(auth()->user()->tokenCan('office.update'),
40 | Response::HTTP_FORBIDDEN
41 | );
42 |
43 | $this->authorize('update', $office);
44 |
45 | throw_if($office->images()->count() == 1,
46 | ValidationException::withMessages(['image' => 'Cannot delete the only image.'])
47 | );
48 |
49 | throw_if($office->featured_image_id == $image->id,
50 | ValidationException::withMessages(['image' => 'Cannot delete the featured image.'])
51 | );
52 |
53 | Storage::delete($image->path);
54 |
55 | $image->delete();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/config/hashing.php:
--------------------------------------------------------------------------------
1 | 'bcrypt',
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Bcrypt Options
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may specify the configuration options that should be used when
26 | | passwords are hashed using the Bcrypt algorithm. This will allow you
27 | | to control the amount of time it takes to hash the given password.
28 | |
29 | */
30 |
31 | 'bcrypt' => [
32 | 'rounds' => env('BCRYPT_ROUNDS', 10),
33 | ],
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Argon Options
38 | |--------------------------------------------------------------------------
39 | |
40 | | Here you may specify the configuration options that should be used when
41 | | passwords are hashed using the Argon algorithm. These will allow you
42 | | to control the amount of time it takes to hash the given password.
43 | |
44 | */
45 |
46 | 'argon' => [
47 | 'memory' => 1024,
48 | 'threads' => 2,
49 | 'time' => 2,
50 | ],
51 |
52 | ];
53 |
--------------------------------------------------------------------------------
/app/Http/Controllers/HostReservationController.php:
--------------------------------------------------------------------------------
1 | user()->tokenCan('reservations.show'),
16 | Response::HTTP_FORBIDDEN
17 | );
18 |
19 | validator(request()->all(), [
20 | 'status' => [Rule::in([Reservation::STATUS_ACTIVE, Reservation::STATUS_CANCELLED])],
21 | 'office_id' => ['integer'],
22 | 'user_id' => ['integer'],
23 | 'from_date' => ['date', 'required_with:to_date'],
24 | 'to_date' => ['date', 'required_with:from_date', 'after:from_date'],
25 | ])->validate();
26 |
27 | $reservations = Reservation::query()
28 | ->whereRelation('office', 'user_id', '=', auth()->id())
29 | ->when(request('office_id'),
30 | fn($query) => $query->where('office_id', request('office_id'))
31 | )->when(request('user_id'),
32 | fn($query) => $query->where('user_id', request('user_id'))
33 | )->when(request('status'),
34 | fn($query) => $query->where('status', request('status'))
35 | )->when(request('from_date') && request('to_date'),
36 | fn($query) => $query->betweenDates(request('from_date'), request('to_date'))
37 | )
38 | ->with(['office.featuredImage'])
39 | ->paginate(20);
40 |
41 | return ReservationResource::collection(
42 | $reservations
43 | );
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/bootstrap/app.php:
--------------------------------------------------------------------------------
1 | singleton(
30 | Illuminate\Contracts\Http\Kernel::class,
31 | App\Http\Kernel::class
32 | );
33 |
34 | $app->singleton(
35 | Illuminate\Contracts\Console\Kernel::class,
36 | App\Console\Kernel::class
37 | );
38 |
39 | $app->singleton(
40 | Illuminate\Contracts\Debug\ExceptionHandler::class,
41 | App\Exceptions\Handler::class
42 | );
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Return The Application
47 | |--------------------------------------------------------------------------
48 | |
49 | | This script returns the application instance. The instance is given to
50 | | the calling script so we can separate the building of the instances
51 | | from the actual running of the application and sending responses.
52 | |
53 | */
54 |
55 | return $app;
56 |
--------------------------------------------------------------------------------
/artisan:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env php
2 | make(Illuminate\Contracts\Console\Kernel::class);
34 |
35 | $status = $kernel->handle(
36 | $input = new Symfony\Component\Console\Input\ArgvInput,
37 | new Symfony\Component\Console\Output\ConsoleOutput
38 | );
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Shutdown The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once Artisan has finished running, we will fire off the shutdown events
46 | | so that any final work may be done by the application before we shut
47 | | down the process. This is the last thing to happen to the request.
48 | |
49 | */
50 |
51 | $kernel->terminate($input, $status);
52 |
53 | exit($status);
54 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## About This Project
2 |
3 | ergodnc (Ergonomic Desk & Coffee) is an open source Laravel project that's being built live on the official Laravel YouTube Channel ([Check Here](https://www.youtube.com/watch?v=2RlbXNjhQkc&list=PLcjapmjyX17gCa-eo19wDXf3fD7H48NP5&ab_channel=Laravel)).
4 |
5 | You can contribute by asking questions, helping others, reporting issues, or opening pull requests.
6 |
7 | ## Learning Laravel
8 |
9 | Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
10 |
11 | If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
12 |
13 | ## Laravel Sponsors
14 |
15 | We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
16 |
17 | ### Laravel Premium Partners
18 |
19 | - **[Vehikl](https://vehikl.com/)**
20 | - **[Tighten Co.](https://tighten.co)**
21 | - **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
22 | - **[64 Robots](https://64robots.com)**
23 | - **[Cubet Techno Labs](https://cubettech.com)**
24 | - **[Cyber-Duck](https://cyber-duck.co.uk)**
25 | - **[Many](https://www.many.co.uk)**
26 | - **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
27 | - **[DevSquad](https://devsquad.com)**
28 | - **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
29 | - **[OP.GG](https://op.gg)**
30 | - **[CMS Max](https://www.cmsmax.com/)**
31 | - **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)**
32 |
--------------------------------------------------------------------------------
/app/Models/Office.php:
--------------------------------------------------------------------------------
1 | 'decimal:8',
23 | 'lng' => 'decimal:8',
24 | 'approval_status' => 'integer',
25 | 'hidden' => 'bool',
26 | 'price_per_day' => 'integer',
27 | 'monthly_discount' => 'integer',
28 | ];
29 |
30 | public function user(): BelongsTo
31 | {
32 | return $this->belongsTo(User::class);
33 | }
34 |
35 | public function reservations(): HasMany
36 | {
37 | return $this->hasMany(Reservation::class);
38 | }
39 |
40 | public function images(): MorphMany
41 | {
42 | return $this->morphMany(Image::class, 'resource');
43 | }
44 |
45 | public function featuredImage(): BelongsTo
46 | {
47 | return $this->belongsTo(Image::class, 'featured_image_id');
48 | }
49 |
50 | public function tags(): BelongsToMany
51 | {
52 | return $this->belongsToMany(Tag::class, 'offices_tags');
53 | }
54 |
55 | public function scopeNearestTo(Builder $builder, $lat, $lng)
56 | {
57 | return $builder
58 | ->select()
59 | ->orderByRaw(
60 | 'POW(69.1 * (lat - ?), 2) + POW(69.1 * (? - lng) * COS(lat / 57.3), 2)',
61 | [$lat, $lng]
62 | );
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/Providers/RouteServiceProvider.php:
--------------------------------------------------------------------------------
1 | configureRateLimiting();
39 |
40 | $this->routes(function () {
41 | Route::middleware('api')
42 | ->namespace($this->namespace)
43 | ->group(base_path('routes/api.php'));
44 |
45 | Route::middleware('web')
46 | ->namespace($this->namespace)
47 | ->group(base_path('routes/web.php'));
48 | });
49 | }
50 |
51 | /**
52 | * Configure the rate limiters for the application.
53 | *
54 | * @return void
55 | */
56 | protected function configureRateLimiting()
57 | {
58 | RateLimiter::for('api', function (Request $request) {
59 | return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
60 | });
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/public/index.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class);
50 |
51 | $response = tap($kernel->handle(
52 | $request = Request::capture()
53 | ))->send();
54 |
55 | $kernel->terminate($request, $response);
56 |
--------------------------------------------------------------------------------
/config/sanctum.php:
--------------------------------------------------------------------------------
1 | explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
17 | '%s%s',
18 | 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
19 | env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
20 | ))),
21 |
22 | /*
23 | |--------------------------------------------------------------------------
24 | | Expiration Minutes
25 | |--------------------------------------------------------------------------
26 | |
27 | | This value controls the number of minutes until an issued token will be
28 | | considered expired. If this value is null, personal access tokens do
29 | | not expire. This won't tweak the lifetime of first-party sessions.
30 | |
31 | */
32 |
33 | 'expiration' => null,
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Sanctum Middleware
38 | |--------------------------------------------------------------------------
39 | |
40 | | When authenticating your first-party SPA with Sanctum you may need to
41 | | customize some of the middleware Sanctum uses while processing the
42 | | request. You may change the middleware listed below as required.
43 | |
44 | */
45 |
46 | 'middleware' => [
47 | 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
48 | 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
49 | ],
50 |
51 | ];
52 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravel/laravel",
3 | "type": "project",
4 | "description": "The Laravel Framework.",
5 | "keywords": ["framework", "laravel"],
6 | "license": "MIT",
7 | "require": {
8 | "php": "^8.0",
9 | "fruitcake/laravel-cors": "^2.0",
10 | "guzzlehttp/guzzle": "^7.0.1",
11 | "laravel/framework": "^8.54",
12 | "laravel/sanctum": "^2.11",
13 | "laravel/tinker": "^2.5"
14 | },
15 | "require-dev": {
16 | "facade/ignition": "^2.5",
17 | "fakerphp/faker": "^1.9.1",
18 | "laravel/sail": "^1.0.1",
19 | "mockery/mockery": "^1.4.2",
20 | "nunomaduro/collision": "^5.0",
21 | "phpunit/phpunit": "^9.3.3"
22 | },
23 | "autoload": {
24 | "psr-4": {
25 | "App\\": "app/",
26 | "Database\\Factories\\": "database/factories/",
27 | "Database\\Seeders\\": "database/seeders/"
28 | }
29 | },
30 | "autoload-dev": {
31 | "psr-4": {
32 | "Tests\\": "tests/"
33 | }
34 | },
35 | "scripts": {
36 | "post-autoload-dump": [
37 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
38 | "@php artisan package:discover --ansi"
39 | ],
40 | "post-update-cmd": [
41 | "@php artisan vendor:publish --tag=laravel-assets --ansi"
42 | ],
43 | "post-root-package-install": [
44 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
45 | ],
46 | "post-create-project-cmd": [
47 | "@php artisan key:generate --ansi"
48 | ]
49 | },
50 | "extra": {
51 | "laravel": {
52 | "dont-discover": []
53 | }
54 | },
55 | "config": {
56 | "optimize-autoloader": true,
57 | "preferred-install": "dist",
58 | "sort-packages": true
59 | },
60 | "minimum-stability": "dev",
61 | "prefer-stable": true
62 | }
63 |
--------------------------------------------------------------------------------
/config/broadcasting.php:
--------------------------------------------------------------------------------
1 | env('BROADCAST_DRIVER', 'null'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Broadcast Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the broadcast connections that will be used
26 | | to broadcast events to other systems or over websockets. Samples of
27 | | each available type of connection are provided inside this array.
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'pusher' => [
34 | 'driver' => 'pusher',
35 | 'key' => env('PUSHER_APP_KEY'),
36 | 'secret' => env('PUSHER_APP_SECRET'),
37 | 'app_id' => env('PUSHER_APP_ID'),
38 | 'options' => [
39 | 'cluster' => env('PUSHER_APP_CLUSTER'),
40 | 'useTLS' => true,
41 | ],
42 | ],
43 |
44 | 'ably' => [
45 | 'driver' => 'ably',
46 | 'key' => env('ABLY_KEY'),
47 | ],
48 |
49 | 'redis' => [
50 | 'driver' => 'redis',
51 | 'connection' => 'default',
52 | ],
53 |
54 | 'log' => [
55 | 'driver' => 'log',
56 | ],
57 |
58 | 'null' => [
59 | 'driver' => 'null',
60 | ],
61 |
62 | ],
63 |
64 | ];
65 |
--------------------------------------------------------------------------------
/routes/api.php:
--------------------------------------------------------------------------------
1 | middleware(['auth:sanctum']);
26 |
27 | // Offices...
28 | Route::get('/offices', [OfficeController::class, 'index']);
29 | Route::get('/offices/{office}', [OfficeController::class, 'show']);
30 | Route::post('/offices', [OfficeController::class, 'create'])->middleware(['auth:sanctum', 'verified']);
31 | Route::put('/offices/{office}', [OfficeController::class, 'update'])->middleware(['auth:sanctum', 'verified']);
32 | Route::delete('/offices/{office}', [OfficeController::class, 'delete'])->middleware(['auth:sanctum', 'verified']);
33 |
34 | // Office Photos...
35 | Route::post('/offices/{office}/images', [OfficeImageController::class, 'store'])->middleware(['auth:sanctum', 'verified']);
36 | Route::delete('/offices/{office}/images/{image:id}', [OfficeImageController::class, 'delete'])->middleware(['auth:sanctum', 'verified']);
37 |
38 | // User Reservations...
39 | Route::get('/reservations', [UserReservationController::class, 'index'])->middleware(['auth:sanctum', 'verified']);
40 | Route::post('/reservations', [UserReservationController::class, 'create'])->middleware(['auth:sanctum', 'verified']);
41 | Route::delete('/reservations/{reservation}', [UserReservationController::class, 'cancel'])->middleware(['auth:sanctum', 'verified']);
42 |
43 | // Host Reservations...
44 | Route::get('/host/reservations', [HostReservationController::class, 'index']);
45 |
--------------------------------------------------------------------------------
/config/filesystems.php:
--------------------------------------------------------------------------------
1 | env('FILESYSTEM_DRIVER', 'local'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Filesystem Disks
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure as many filesystem "disks" as you wish, and you
24 | | may even configure multiple disks of the same driver. Defaults have
25 | | been setup for each driver as an example of the required options.
26 | |
27 | | Supported Drivers: "local", "ftp", "sftp", "s3"
28 | |
29 | */
30 |
31 | 'disks' => [
32 |
33 | 'local' => [
34 | 'driver' => 'local',
35 | 'root' => storage_path('app'),
36 | ],
37 |
38 | 'public' => [
39 | 'driver' => 'local',
40 | 'root' => storage_path('app/public'),
41 | 'url' => env('APP_URL').'/storage',
42 | 'visibility' => 'public',
43 | ],
44 |
45 | 's3' => [
46 | 'driver' => 's3',
47 | 'key' => env('AWS_ACCESS_KEY_ID'),
48 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
49 | 'region' => env('AWS_DEFAULT_REGION'),
50 | 'bucket' => env('AWS_BUCKET'),
51 | 'url' => env('AWS_URL'),
52 | 'endpoint' => env('AWS_ENDPOINT'),
53 | 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
54 | ],
55 |
56 | ],
57 |
58 | /*
59 | |--------------------------------------------------------------------------
60 | | Symbolic Links
61 | |--------------------------------------------------------------------------
62 | |
63 | | Here you may configure the symbolic links that will be created when the
64 | | `storage:link` Artisan command is executed. The array keys should be
65 | | the locations of the links and the values should be their targets.
66 | |
67 | */
68 |
69 | 'links' => [
70 | public_path('storage') => storage_path('app/public'),
71 | ],
72 |
73 | ];
74 |
--------------------------------------------------------------------------------
/app/Http/Kernel.php:
--------------------------------------------------------------------------------
1 | [
33 | \App\Http\Middleware\EncryptCookies::class,
34 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
35 | \Illuminate\Session\Middleware\StartSession::class,
36 | // \Illuminate\Session\Middleware\AuthenticateSession::class,
37 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
38 | \App\Http\Middleware\VerifyCsrfToken::class,
39 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
40 | ],
41 |
42 | 'api' => [
43 | \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
44 | 'throttle:api',
45 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
46 | ],
47 | ];
48 |
49 | /**
50 | * The application's route middleware.
51 | *
52 | * These middleware may be assigned to groups or used individually.
53 | *
54 | * @var array
55 | */
56 | protected $routeMiddleware = [
57 | 'auth' => \App\Http\Middleware\Authenticate::class,
58 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
59 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
60 | 'can' => \Illuminate\Auth\Middleware\Authorize::class,
61 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
62 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
63 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
64 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
65 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
66 | ];
67 | }
68 |
--------------------------------------------------------------------------------
/config/queue.php:
--------------------------------------------------------------------------------
1 | env('QUEUE_CONNECTION', 'sync'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Queue Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the connection information for each server that
24 | | is used by your application. A default configuration has been added
25 | | for each back-end shipped with Laravel. You are free to add more.
26 | |
27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'sync' => [
34 | 'driver' => 'sync',
35 | ],
36 |
37 | 'database' => [
38 | 'driver' => 'database',
39 | 'table' => 'jobs',
40 | 'queue' => 'default',
41 | 'retry_after' => 90,
42 | 'after_commit' => false,
43 | ],
44 |
45 | 'beanstalkd' => [
46 | 'driver' => 'beanstalkd',
47 | 'host' => 'localhost',
48 | 'queue' => 'default',
49 | 'retry_after' => 90,
50 | 'block_for' => 0,
51 | 'after_commit' => false,
52 | ],
53 |
54 | 'sqs' => [
55 | 'driver' => 'sqs',
56 | 'key' => env('AWS_ACCESS_KEY_ID'),
57 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
58 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
59 | 'queue' => env('SQS_QUEUE', 'default'),
60 | 'suffix' => env('SQS_SUFFIX'),
61 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
62 | 'after_commit' => false,
63 | ],
64 |
65 | 'redis' => [
66 | 'driver' => 'redis',
67 | 'connection' => 'default',
68 | 'queue' => env('REDIS_QUEUE', 'default'),
69 | 'retry_after' => 90,
70 | 'block_for' => null,
71 | 'after_commit' => false,
72 | ],
73 |
74 | ],
75 |
76 | /*
77 | |--------------------------------------------------------------------------
78 | | Failed Queue Jobs
79 | |--------------------------------------------------------------------------
80 | |
81 | | These options configure the behavior of failed queue job logging so you
82 | | can control which database and table are used to store the jobs that
83 | | have failed. You may change them to any database / table you wish.
84 | |
85 | */
86 |
87 | 'failed' => [
88 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
89 | 'database' => env('DB_CONNECTION', 'mysql'),
90 | 'table' => 'failed_jobs',
91 | ],
92 |
93 | ];
94 |
--------------------------------------------------------------------------------
/config/logging.php:
--------------------------------------------------------------------------------
1 | env('LOG_CHANNEL', 'stack'),
21 |
22 | /*
23 | |--------------------------------------------------------------------------
24 | | Log Channels
25 | |--------------------------------------------------------------------------
26 | |
27 | | Here you may configure the log channels for your application. Out of
28 | | the box, Laravel uses the Monolog PHP logging library. This gives
29 | | you a variety of powerful log handlers / formatters to utilize.
30 | |
31 | | Available Drivers: "single", "daily", "slack", "syslog",
32 | | "errorlog", "monolog",
33 | | "custom", "stack"
34 | |
35 | */
36 |
37 | 'channels' => [
38 | 'stack' => [
39 | 'driver' => 'stack',
40 | 'channels' => ['single'],
41 | 'ignore_exceptions' => false,
42 | ],
43 |
44 | 'single' => [
45 | 'driver' => 'single',
46 | 'path' => storage_path('logs/laravel.log'),
47 | 'level' => env('LOG_LEVEL', 'debug'),
48 | ],
49 |
50 | 'daily' => [
51 | 'driver' => 'daily',
52 | 'path' => storage_path('logs/laravel.log'),
53 | 'level' => env('LOG_LEVEL', 'debug'),
54 | 'days' => 14,
55 | ],
56 |
57 | 'slack' => [
58 | 'driver' => 'slack',
59 | 'url' => env('LOG_SLACK_WEBHOOK_URL'),
60 | 'username' => 'Laravel Log',
61 | 'emoji' => ':boom:',
62 | 'level' => env('LOG_LEVEL', 'critical'),
63 | ],
64 |
65 | 'papertrail' => [
66 | 'driver' => 'monolog',
67 | 'level' => env('LOG_LEVEL', 'debug'),
68 | 'handler' => SyslogUdpHandler::class,
69 | 'handler_with' => [
70 | 'host' => env('PAPERTRAIL_URL'),
71 | 'port' => env('PAPERTRAIL_PORT'),
72 | ],
73 | ],
74 |
75 | 'stderr' => [
76 | 'driver' => 'monolog',
77 | 'level' => env('LOG_LEVEL', 'debug'),
78 | 'handler' => StreamHandler::class,
79 | 'formatter' => env('LOG_STDERR_FORMATTER'),
80 | 'with' => [
81 | 'stream' => 'php://stderr',
82 | ],
83 | ],
84 |
85 | 'syslog' => [
86 | 'driver' => 'syslog',
87 | 'level' => env('LOG_LEVEL', 'debug'),
88 | ],
89 |
90 | 'errorlog' => [
91 | 'driver' => 'errorlog',
92 | 'level' => env('LOG_LEVEL', 'debug'),
93 | ],
94 |
95 | 'null' => [
96 | 'driver' => 'monolog',
97 | 'handler' => NullHandler::class,
98 | ],
99 |
100 | 'emergency' => [
101 | 'path' => storage_path('logs/laravel.log'),
102 | ],
103 | ],
104 |
105 | ];
106 |
--------------------------------------------------------------------------------
/config/cache.php:
--------------------------------------------------------------------------------
1 | env('CACHE_DRIVER', 'file'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Cache Stores
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the cache "stores" for your application as
26 | | well as their drivers. You may even define multiple stores for the
27 | | same cache driver to group types of items stored in your caches.
28 | |
29 | | Supported drivers: "apc", "array", "database", "file",
30 | | "memcached", "redis", "dynamodb", "octane", "null"
31 | |
32 | */
33 |
34 | 'stores' => [
35 |
36 | 'apc' => [
37 | 'driver' => 'apc',
38 | ],
39 |
40 | 'array' => [
41 | 'driver' => 'array',
42 | 'serialize' => false,
43 | ],
44 |
45 | 'database' => [
46 | 'driver' => 'database',
47 | 'table' => 'cache',
48 | 'connection' => null,
49 | 'lock_connection' => null,
50 | ],
51 |
52 | 'file' => [
53 | 'driver' => 'file',
54 | 'path' => storage_path('framework/cache/data'),
55 | ],
56 |
57 | 'memcached' => [
58 | 'driver' => 'memcached',
59 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
60 | 'sasl' => [
61 | env('MEMCACHED_USERNAME'),
62 | env('MEMCACHED_PASSWORD'),
63 | ],
64 | 'options' => [
65 | // Memcached::OPT_CONNECT_TIMEOUT => 2000,
66 | ],
67 | 'servers' => [
68 | [
69 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
70 | 'port' => env('MEMCACHED_PORT', 11211),
71 | 'weight' => 100,
72 | ],
73 | ],
74 | ],
75 |
76 | 'redis' => [
77 | 'driver' => 'redis',
78 | 'connection' => 'cache',
79 | 'lock_connection' => 'default',
80 | ],
81 |
82 | 'dynamodb' => [
83 | 'driver' => 'dynamodb',
84 | 'key' => env('AWS_ACCESS_KEY_ID'),
85 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
86 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
87 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
88 | 'endpoint' => env('DYNAMODB_ENDPOINT'),
89 | ],
90 |
91 | 'octane' => [
92 | 'driver' => 'octane',
93 | ],
94 |
95 | ],
96 |
97 | /*
98 | |--------------------------------------------------------------------------
99 | | Cache Key Prefix
100 | |--------------------------------------------------------------------------
101 | |
102 | | When utilizing a RAM based store such as APC or Memcached, there might
103 | | be other applications utilizing the same cache. So, we'll specify a
104 | | value to get prefixed to all our keys so we can avoid collisions.
105 | |
106 | */
107 |
108 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
109 |
110 | ];
111 |
--------------------------------------------------------------------------------
/config/mail.php:
--------------------------------------------------------------------------------
1 | env('MAIL_MAILER', 'smtp'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Mailer Configurations
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure all of the mailers used by your application plus
24 | | their respective settings. Several examples have been configured for
25 | | you and you are free to add your own as your application requires.
26 | |
27 | | Laravel supports a variety of mail "transport" drivers to be used while
28 | | sending an e-mail. You will specify which one you are using for your
29 | | mailers below. You are free to add additional mailers as required.
30 | |
31 | | Supported: "smtp", "sendmail", "mailgun", "ses",
32 | | "postmark", "log", "array"
33 | |
34 | */
35 |
36 | 'mailers' => [
37 | 'smtp' => [
38 | 'transport' => 'smtp',
39 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
40 | 'port' => env('MAIL_PORT', 587),
41 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'),
42 | 'username' => env('MAIL_USERNAME'),
43 | 'password' => env('MAIL_PASSWORD'),
44 | 'timeout' => null,
45 | 'auth_mode' => null,
46 | ],
47 |
48 | 'ses' => [
49 | 'transport' => 'ses',
50 | ],
51 |
52 | 'mailgun' => [
53 | 'transport' => 'mailgun',
54 | ],
55 |
56 | 'postmark' => [
57 | 'transport' => 'postmark',
58 | ],
59 |
60 | 'sendmail' => [
61 | 'transport' => 'sendmail',
62 | 'path' => '/usr/sbin/sendmail -bs',
63 | ],
64 |
65 | 'log' => [
66 | 'transport' => 'log',
67 | 'channel' => env('MAIL_LOG_CHANNEL'),
68 | ],
69 |
70 | 'array' => [
71 | 'transport' => 'array',
72 | ],
73 |
74 | 'failover' => [
75 | 'transport' => 'failover',
76 | 'mailers' => [
77 | 'smtp',
78 | 'log',
79 | ],
80 | ],
81 | ],
82 |
83 | /*
84 | |--------------------------------------------------------------------------
85 | | Global "From" Address
86 | |--------------------------------------------------------------------------
87 | |
88 | | You may wish for all e-mails sent by your application to be sent from
89 | | the same address. Here, you may specify a name and address that is
90 | | used globally for all e-mails that are sent by your application.
91 | |
92 | */
93 |
94 | 'from' => [
95 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
96 | 'name' => env('MAIL_FROM_NAME', 'Example'),
97 | ],
98 |
99 | /*
100 | |--------------------------------------------------------------------------
101 | | Markdown Mail Settings
102 | |--------------------------------------------------------------------------
103 | |
104 | | If you are using Markdown based email rendering, you may configure your
105 | | theme and component paths here, allowing you to customize the design
106 | | of the emails. Or, you may simply stick with the Laravel defaults!
107 | |
108 | */
109 |
110 | 'markdown' => [
111 | 'theme' => 'default',
112 |
113 | 'paths' => [
114 | resource_path('views/vendor/mail'),
115 | ],
116 | ],
117 |
118 | ];
119 |
--------------------------------------------------------------------------------
/tests/Feature/OfficeImageControllerTest.php:
--------------------------------------------------------------------------------
1 | create();
26 | $office = Office::factory()->for($user)->create();
27 |
28 | $this->actingAs($user);
29 |
30 | $response = $this->post("/offices/{$office->id}/images", [
31 | 'image' => UploadedFile::fake()->image('image.jpg')
32 | ]);
33 |
34 | $response->assertCreated();
35 |
36 | // @TODO This test is failing and needs investigation
37 | // Storage::assertExists(
38 | // $response->json('data.path')
39 | // );
40 | }
41 |
42 | /**
43 | * @test
44 | */
45 | public function itDeletesAnImage()
46 | {
47 | Storage::put('/office_image.jpg', 'empty');
48 |
49 | $user = User::factory()->create();
50 | $office = Office::factory()->for($user)->create();
51 |
52 | $office->images()->create([
53 | 'path' => 'image.jpg'
54 | ]);
55 |
56 | $image = $office->images()->create([
57 | 'path' => 'office_image.jpg'
58 | ]);
59 |
60 | $this->actingAs($user);
61 |
62 | $response = $this->deleteJson("/offices/{$office->id}/images/{$image->id}");
63 |
64 | $response->assertOk();
65 |
66 | $this->assertModelMissing($image);
67 |
68 | Storage::assertMissing('office_image.jpg');
69 | }
70 |
71 | /**
72 | * @test
73 | */
74 | public function itDoesntDeleteImageThatBelongsToAnotherResource()
75 | {
76 | $user = User::factory()->create();
77 | $office = Office::factory()->for($user)->create();
78 | $office2 = Office::factory()->for($user)->create();
79 |
80 | $image = $office2->images()->create([
81 | 'path' => 'office_image.jpg'
82 | ]);
83 |
84 | $this->actingAs($user);
85 |
86 | $response = $this->deleteJson("/offices/{$office->id}/images/{$image->id}");
87 |
88 | $response->assertNotFound();
89 | }
90 |
91 | /**
92 | * @test
93 | */
94 | public function itDoesntDeleteTheOnlyImage()
95 | {
96 | $user = User::factory()->create();
97 | $office = Office::factory()->for($user)->create();
98 |
99 | $image = $office->images()->create([
100 | 'path' => 'office_image.jpg'
101 | ]);
102 |
103 | $this->actingAs($user);
104 |
105 | $response = $this->deleteJson("/offices/{$office->id}/images/{$image->id}");
106 |
107 | $response->assertUnprocessable();
108 |
109 | $response->assertJsonValidationErrors(['image' => 'Cannot delete the only image.']);
110 | }
111 |
112 | /**
113 | * @test
114 | */
115 | public function itDoesntDeleteTheFeaturedImage()
116 | {
117 | $user = User::factory()->create();
118 | $office = Office::factory()->for($user)->create();
119 |
120 | $office->images()->create([
121 | 'path' => 'image.jpg'
122 | ]);
123 |
124 | $image = $office->images()->create([
125 | 'path' => 'office_image.jpg'
126 | ]);
127 |
128 | $office->update(['featured_image_id' => $image->id]);
129 |
130 | $this->actingAs($user);
131 |
132 | $response = $this->deleteJson("/offices/{$office->id}/images/{$image->id}");
133 |
134 | $response->assertUnprocessable();
135 |
136 | $response->assertJsonValidationErrors(['image' => 'Cannot delete the featured image.']);
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/config/auth.php:
--------------------------------------------------------------------------------
1 | [
17 | 'guard' => 'sanctum',
18 | 'passwords' => 'users',
19 | ],
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | Authentication Guards
24 | |--------------------------------------------------------------------------
25 | |
26 | | Next, you may define every authentication guard for your application.
27 | | Of course, a great default configuration has been defined for you
28 | | here which uses session storage and the Eloquent user provider.
29 | |
30 | | All authentication drivers have a user provider. This defines how the
31 | | users are actually retrieved out of your database or other storage
32 | | mechanisms used by this application to persist your user's data.
33 | |
34 | | Supported: "session"
35 | |
36 | */
37 |
38 | 'guards' => [
39 | 'web' => [
40 | 'driver' => 'session',
41 | 'provider' => 'users',
42 | ],
43 | ],
44 |
45 | /*
46 | |--------------------------------------------------------------------------
47 | | User Providers
48 | |--------------------------------------------------------------------------
49 | |
50 | | All authentication drivers have a user provider. This defines how the
51 | | users are actually retrieved out of your database or other storage
52 | | mechanisms used by this application to persist your user's data.
53 | |
54 | | If you have multiple user tables or models you may configure multiple
55 | | sources which represent each model / table. These sources may then
56 | | be assigned to any extra authentication guards you have defined.
57 | |
58 | | Supported: "database", "eloquent"
59 | |
60 | */
61 |
62 | 'providers' => [
63 | 'users' => [
64 | 'driver' => 'eloquent',
65 | 'model' => App\Models\User::class,
66 | ],
67 |
68 | // 'users' => [
69 | // 'driver' => 'database',
70 | // 'table' => 'users',
71 | // ],
72 | ],
73 |
74 | /*
75 | |--------------------------------------------------------------------------
76 | | Resetting Passwords
77 | |--------------------------------------------------------------------------
78 | |
79 | | You may specify multiple password reset configurations if you have more
80 | | than one user table or model in the application and you want to have
81 | | separate password reset settings based on the specific user types.
82 | |
83 | | The expire time is the number of minutes that the reset token should be
84 | | considered valid. This security feature keeps tokens short-lived so
85 | | they have less time to be guessed. You may change this as needed.
86 | |
87 | */
88 |
89 | 'passwords' => [
90 | 'users' => [
91 | 'provider' => 'users',
92 | 'table' => 'password_resets',
93 | 'expire' => 60,
94 | 'throttle' => 60,
95 | ],
96 | ],
97 |
98 | /*
99 | |--------------------------------------------------------------------------
100 | | Password Confirmation Timeout
101 | |--------------------------------------------------------------------------
102 | |
103 | | Here you may define the amount of seconds before a password confirmation
104 | | times out and the user is prompted to re-enter their password via the
105 | | confirmation screen. By default, the timeout lasts for three hours.
106 | |
107 | */
108 |
109 | 'password_timeout' => 10800,
110 |
111 | ];
112 |
--------------------------------------------------------------------------------
/app/Http/Controllers/OfficeController.php:
--------------------------------------------------------------------------------
1 | when(request('user_id') && auth()->user() && request('user_id') == auth()->id(),
26 | fn($builder) => $builder,
27 | fn($builder) => $builder->where('approval_status', Office::APPROVAL_APPROVED)->where('hidden', false)
28 | )
29 | ->when(request('user_id'), fn($builder) => $builder->whereUserId(request('user_id')))
30 | ->when(request('visitor_id'),
31 | fn($builder) => $builder->whereRelation('reservations', 'user_id', '=', request('visitor_id'))
32 | )
33 | ->when(
34 | request('lat') && request('lng'),
35 | fn($builder) => $builder->nearestTo(request('lat'), request('lng')),
36 | fn($builder) => $builder->orderBy('id', 'ASC')
37 | )
38 | ->when(request('tags'),
39 | fn($builder) => $builder->whereHas(
40 | 'tags',
41 | fn ($builder) => $builder->whereIn('id', request('tags')),
42 | '=',
43 | count(request('tags'))
44 | )
45 | )
46 | ->with(['images', 'tags', 'user'])
47 | ->withCount(['reservations' => fn($builder) => $builder->whereStatus(Reservation::STATUS_ACTIVE)])
48 | ->paginate(20);
49 |
50 | return OfficeResource::collection(
51 | $offices
52 | );
53 | }
54 |
55 | public function show(Office $office): JsonResource
56 | {
57 | $office->loadCount(['reservations' => fn($builder) => $builder->where('status', Reservation::STATUS_ACTIVE)])
58 | ->load(['images', 'tags', 'user']);
59 |
60 | return OfficeResource::make($office);
61 | }
62 |
63 | public function create(): JsonResource
64 | {
65 | abort_unless(auth()->user()->tokenCan('office.create'),
66 | Response::HTTP_FORBIDDEN
67 | );
68 |
69 | $attributes = (new OfficeValidator())->validate(
70 | $office = new Office(),
71 | request()->all()
72 | );
73 |
74 | $attributes['approval_status'] = Office::APPROVAL_PENDING;
75 | $attributes['user_id'] = auth()->id();
76 |
77 | $office = DB::transaction(function () use ($office, $attributes) {
78 | $office->fill(
79 | Arr::except($attributes, ['tags'])
80 | )->save();
81 |
82 | if (isset($attributes['tags'])) {
83 | $office->tags()->attach($attributes['tags']);
84 | }
85 |
86 | return $office;
87 | });
88 |
89 | Notification::send(User::where('is_admin', true)->get(), new OfficePendingApproval($office));
90 |
91 | return OfficeResource::make(
92 | $office->load(['images', 'tags', 'user'])
93 | );
94 | }
95 |
96 | public function update(Office $office): JsonResource
97 | {
98 | abort_unless(auth()->user()->tokenCan('office.update'),
99 | Response::HTTP_FORBIDDEN
100 | );
101 |
102 | $this->authorize('update', $office);
103 |
104 | $attributes = (new OfficeValidator())->validate($office, request()->all());
105 |
106 | $office->fill(Arr::except($attributes, ['tags']));
107 |
108 | if ($requiresReview = $office->isDirty(['lat', 'lng', 'price_per_day'])) {
109 | $office->fill(['approval_status' => Office::APPROVAL_PENDING]);
110 | }
111 |
112 | DB::transaction(function () use ($office, $attributes) {
113 | $office->save();
114 |
115 | if (isset($attributes['tags'])) {
116 | $office->tags()->sync($attributes['tags']);
117 | }
118 | });
119 |
120 | if ($requiresReview) {
121 | Notification::send(User::where('is_admin', true)->get(), new OfficePendingApproval($office));
122 | }
123 |
124 | return OfficeResource::make(
125 | $office->load(['images', 'tags', 'user'])
126 | );
127 | }
128 |
129 | public function delete(Office $office)
130 | {
131 | abort_unless(auth()->user()->tokenCan('office.delete'),
132 | Response::HTTP_FORBIDDEN
133 | );
134 |
135 | $this->authorize('delete', $office);
136 |
137 | throw_if(
138 | $office->reservations()->where('status', Reservation::STATUS_ACTIVE)->exists(),
139 | ValidationException::withMessages(['office' => 'Cannot delete this office!'])
140 | );
141 |
142 | $office->images()->each(function ($image) {
143 | Storage::delete($image->path);
144 |
145 | $image->delete();
146 | });
147 |
148 | $office->delete();
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/config/database.php:
--------------------------------------------------------------------------------
1 | env('DB_CONNECTION', 'mysql'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Database Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here are each of the database connections setup for your application.
26 | | Of course, examples of configuring each database platform that is
27 | | supported by Laravel is shown below to make development simple.
28 | |
29 | |
30 | | All database work in Laravel is done through the PHP PDO facilities
31 | | so make sure you have the driver for your particular database of
32 | | choice installed on your machine before you begin development.
33 | |
34 | */
35 |
36 | 'connections' => [
37 |
38 | 'sqlite' => [
39 | 'driver' => 'sqlite',
40 | 'url' => env('DATABASE_URL'),
41 | 'database' => env('DB_DATABASE', database_path('database.sqlite')),
42 | 'prefix' => '',
43 | 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
44 | ],
45 |
46 | 'mysql' => [
47 | 'driver' => 'mysql',
48 | 'url' => env('DATABASE_URL'),
49 | 'host' => env('DB_HOST', '127.0.0.1'),
50 | 'port' => env('DB_PORT', '3306'),
51 | 'database' => env('DB_DATABASE', 'forge'),
52 | 'username' => env('DB_USERNAME', 'forge'),
53 | 'password' => env('DB_PASSWORD', ''),
54 | 'unix_socket' => env('DB_SOCKET', ''),
55 | 'charset' => 'utf8mb4',
56 | 'collation' => 'utf8mb4_unicode_ci',
57 | 'prefix' => '',
58 | 'prefix_indexes' => true,
59 | 'strict' => true,
60 | 'engine' => null,
61 | 'options' => extension_loaded('pdo_mysql') ? array_filter([
62 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
63 | ]) : [],
64 | ],
65 |
66 | 'pgsql' => [
67 | 'driver' => 'pgsql',
68 | 'url' => env('DATABASE_URL'),
69 | 'host' => env('DB_HOST', '127.0.0.1'),
70 | 'port' => env('DB_PORT', '5432'),
71 | 'database' => env('DB_DATABASE', 'forge'),
72 | 'username' => env('DB_USERNAME', 'forge'),
73 | 'password' => env('DB_PASSWORD', ''),
74 | 'charset' => 'utf8',
75 | 'prefix' => '',
76 | 'prefix_indexes' => true,
77 | 'schema' => 'public',
78 | 'sslmode' => 'prefer',
79 | ],
80 |
81 | 'sqlsrv' => [
82 | 'driver' => 'sqlsrv',
83 | 'url' => env('DATABASE_URL'),
84 | 'host' => env('DB_HOST', 'localhost'),
85 | 'port' => env('DB_PORT', '1433'),
86 | 'database' => env('DB_DATABASE', 'forge'),
87 | 'username' => env('DB_USERNAME', 'forge'),
88 | 'password' => env('DB_PASSWORD', ''),
89 | 'charset' => 'utf8',
90 | 'prefix' => '',
91 | 'prefix_indexes' => true,
92 | ],
93 |
94 | ],
95 |
96 | /*
97 | |--------------------------------------------------------------------------
98 | | Migration Repository Table
99 | |--------------------------------------------------------------------------
100 | |
101 | | This table keeps track of all the migrations that have already run for
102 | | your application. Using this information, we can determine which of
103 | | the migrations on disk haven't actually been run in the database.
104 | |
105 | */
106 |
107 | 'migrations' => 'migrations',
108 |
109 | /*
110 | |--------------------------------------------------------------------------
111 | | Redis Databases
112 | |--------------------------------------------------------------------------
113 | |
114 | | Redis is an open source, fast, and advanced key-value store that also
115 | | provides a richer body of commands than a typical key-value system
116 | | such as APC or Memcached. Laravel makes it easy to dig right in.
117 | |
118 | */
119 |
120 | 'redis' => [
121 |
122 | 'client' => env('REDIS_CLIENT', 'phpredis'),
123 |
124 | 'options' => [
125 | 'cluster' => env('REDIS_CLUSTER', 'redis'),
126 | 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
127 | ],
128 |
129 | 'default' => [
130 | 'url' => env('REDIS_URL'),
131 | 'host' => env('REDIS_HOST', '127.0.0.1'),
132 | 'password' => env('REDIS_PASSWORD', null),
133 | 'port' => env('REDIS_PORT', '6379'),
134 | 'database' => env('REDIS_DB', '0'),
135 | ],
136 |
137 | 'cache' => [
138 | 'url' => env('REDIS_URL'),
139 | 'host' => env('REDIS_HOST', '127.0.0.1'),
140 | 'password' => env('REDIS_PASSWORD', null),
141 | 'port' => env('REDIS_PORT', '6379'),
142 | 'database' => env('REDIS_CACHE_DB', '1'),
143 | ],
144 |
145 | ],
146 |
147 | ];
148 |
--------------------------------------------------------------------------------
/app/Http/Controllers/UserReservationController.php:
--------------------------------------------------------------------------------
1 | user()->tokenCan('reservations.show'),
25 | Response::HTTP_FORBIDDEN
26 | );
27 |
28 | validator(request()->all(), [
29 | 'status' => [Rule::in([Reservation::STATUS_ACTIVE, Reservation::STATUS_CANCELLED])],
30 | 'office_id' => ['integer'],
31 | 'from_date' => ['date', 'required_with:to_date'],
32 | 'to_date' => ['date', 'required_with:from_date', 'after:from_date'],
33 | ])->validate();
34 |
35 | $reservations = Reservation::query()
36 | ->where('user_id', auth()->id())
37 | ->when(request('office_id'),
38 | fn($query) => $query->where('office_id', request('office_id'))
39 | )->when(request('status'),
40 | fn($query) => $query->where('status', request('status'))
41 | )->when(request('from_date') && request('to_date'),
42 | fn($query) => $query->betweenDates(request('from_date'), request('to_date'))
43 | )
44 | ->with(['office.featuredImage'])
45 | ->paginate(20);
46 |
47 | return ReservationResource::collection(
48 | $reservations
49 | );
50 | }
51 |
52 | public function create()
53 | {
54 | abort_unless(auth()->user()->tokenCan('reservations.make'),
55 | Response::HTTP_FORBIDDEN
56 | );
57 |
58 | $data = validator(request()->all(), [
59 | 'office_id' => ['required', 'integer'],
60 | 'start_date' => ['required', 'date:Y-m-d', 'after:today'],
61 | 'end_date' => ['required', 'date:Y-m-d', 'after:start_date'],
62 | ])->validate();
63 |
64 | try {
65 | $office = Office::findOrFail($data['office_id']);
66 | } catch (ModelNotFoundException $e) {
67 | throw ValidationException::withMessages([
68 | 'office_id' => 'Invalid office_id'
69 | ]);
70 | }
71 |
72 | if ($office->user_id == auth()->id()) {
73 | throw ValidationException::withMessages([
74 | 'office_id' => 'You cannot make a reservation on your own office'
75 | ]);
76 | }
77 |
78 | if ($office->hidden || $office->approval_status == Office::APPROVAL_PENDING) {
79 | throw ValidationException::withMessages([
80 | 'office_id' => 'You cannot make a reservation on a hidden office'
81 | ]);
82 | }
83 |
84 | $reservation = Cache::lock('reservations_office_'.$office->id, 10)->block(3, function () use ($data, $office) {
85 | $numberOfDays = Carbon::parse($data['end_date'])->endOfDay()->diffInDays(
86 | Carbon::parse($data['start_date'])->startOfDay()
87 | ) + 1;
88 |
89 | if ($office->reservations()->activeBetween($data['start_date'], $data['end_date'])->exists()) {
90 | throw ValidationException::withMessages([
91 | 'office_id' => 'You cannot make a reservation during this time'
92 | ]);
93 | }
94 |
95 | $price = $numberOfDays * $office->price_per_day;
96 |
97 | if ($numberOfDays >= 28 && $office->monthly_discount) {
98 | $price = $price - ($price * $office->monthly_discount / 100);
99 | }
100 |
101 | return Reservation::create([
102 | 'user_id' => auth()->id(),
103 | 'office_id' => $office->id,
104 | 'start_date' => $data['start_date'],
105 | 'end_date' => $data['end_date'],
106 | 'status' => Reservation::STATUS_ACTIVE,
107 | 'price' => $price,
108 | 'wifi_password' => Str::random()
109 | ]);
110 | });
111 |
112 | Notification::send(auth()->user(), new NewUserReservation($reservation));
113 | Notification::send($office->user, new NewHostReservation($reservation));
114 |
115 | return ReservationResource::make(
116 | $reservation->load('office')
117 | );
118 | }
119 |
120 | public function cancel(Reservation $reservation)
121 | {
122 | abort_unless(auth()->user()->tokenCan('reservations.cancel'),
123 | Response::HTTP_FORBIDDEN
124 | );
125 |
126 | if ($reservation->user_id != auth()->id() ||
127 | $reservation->status == Reservation::STATUS_CANCELLED ||
128 | $reservation->start_date < now()->toDateString()) {
129 | throw ValidationException::withMessages([
130 | 'reservation' => 'You cannot cancel this reservation'
131 | ]);
132 | }
133 |
134 | $reservation->update([
135 | 'status' => Reservation::STATUS_CANCELLED
136 | ]);
137 |
138 | return ReservationResource::make(
139 | $reservation->load('office')
140 | );
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/config/session.php:
--------------------------------------------------------------------------------
1 | env('SESSION_DRIVER', 'file'),
22 |
23 | /*
24 | |--------------------------------------------------------------------------
25 | | Session Lifetime
26 | |--------------------------------------------------------------------------
27 | |
28 | | Here you may specify the number of minutes that you wish the session
29 | | to be allowed to remain idle before it expires. If you want them
30 | | to immediately expire on the browser closing, set that option.
31 | |
32 | */
33 |
34 | 'lifetime' => env('SESSION_LIFETIME', 120),
35 |
36 | 'expire_on_close' => false,
37 |
38 | /*
39 | |--------------------------------------------------------------------------
40 | | Session Encryption
41 | |--------------------------------------------------------------------------
42 | |
43 | | This option allows you to easily specify that all of your session data
44 | | should be encrypted before it is stored. All encryption will be run
45 | | automatically by Laravel and you can use the Session like normal.
46 | |
47 | */
48 |
49 | 'encrypt' => false,
50 |
51 | /*
52 | |--------------------------------------------------------------------------
53 | | Session File Location
54 | |--------------------------------------------------------------------------
55 | |
56 | | When using the native session driver, we need a location where session
57 | | files may be stored. A default has been set for you but a different
58 | | location may be specified. This is only needed for file sessions.
59 | |
60 | */
61 |
62 | 'files' => storage_path('framework/sessions'),
63 |
64 | /*
65 | |--------------------------------------------------------------------------
66 | | Session Database Connection
67 | |--------------------------------------------------------------------------
68 | |
69 | | When using the "database" or "redis" session drivers, you may specify a
70 | | connection that should be used to manage these sessions. This should
71 | | correspond to a connection in your database configuration options.
72 | |
73 | */
74 |
75 | 'connection' => env('SESSION_CONNECTION', null),
76 |
77 | /*
78 | |--------------------------------------------------------------------------
79 | | Session Database Table
80 | |--------------------------------------------------------------------------
81 | |
82 | | When using the "database" session driver, you may specify the table we
83 | | should use to manage the sessions. Of course, a sensible default is
84 | | provided for you; however, you are free to change this as needed.
85 | |
86 | */
87 |
88 | 'table' => 'sessions',
89 |
90 | /*
91 | |--------------------------------------------------------------------------
92 | | Session Cache Store
93 | |--------------------------------------------------------------------------
94 | |
95 | | While using one of the framework's cache driven session backends you may
96 | | list a cache store that should be used for these sessions. This value
97 | | must match with one of the application's configured cache "stores".
98 | |
99 | | Affects: "apc", "dynamodb", "memcached", "redis"
100 | |
101 | */
102 |
103 | 'store' => env('SESSION_STORE', null),
104 |
105 | /*
106 | |--------------------------------------------------------------------------
107 | | Session Sweeping Lottery
108 | |--------------------------------------------------------------------------
109 | |
110 | | Some session drivers must manually sweep their storage location to get
111 | | rid of old sessions from storage. Here are the chances that it will
112 | | happen on a given request. By default, the odds are 2 out of 100.
113 | |
114 | */
115 |
116 | 'lottery' => [2, 100],
117 |
118 | /*
119 | |--------------------------------------------------------------------------
120 | | Session Cookie Name
121 | |--------------------------------------------------------------------------
122 | |
123 | | Here you may change the name of the cookie used to identify a session
124 | | instance by ID. The name specified here will get used every time a
125 | | new session cookie is created by the framework for every driver.
126 | |
127 | */
128 |
129 | 'cookie' => env(
130 | 'SESSION_COOKIE',
131 | Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
132 | ),
133 |
134 | /*
135 | |--------------------------------------------------------------------------
136 | | Session Cookie Path
137 | |--------------------------------------------------------------------------
138 | |
139 | | The session cookie path determines the path for which the cookie will
140 | | be regarded as available. Typically, this will be the root path of
141 | | your application but you are free to change this when necessary.
142 | |
143 | */
144 |
145 | 'path' => '/',
146 |
147 | /*
148 | |--------------------------------------------------------------------------
149 | | Session Cookie Domain
150 | |--------------------------------------------------------------------------
151 | |
152 | | Here you may change the domain of the cookie used to identify a session
153 | | in your application. This will determine which domains the cookie is
154 | | available to in your application. A sensible default has been set.
155 | |
156 | */
157 |
158 | 'domain' => env('SESSION_DOMAIN', null),
159 |
160 | /*
161 | |--------------------------------------------------------------------------
162 | | HTTPS Only Cookies
163 | |--------------------------------------------------------------------------
164 | |
165 | | By setting this option to true, session cookies will only be sent back
166 | | to the server if the browser has a HTTPS connection. This will keep
167 | | the cookie from being sent to you when it can't be done securely.
168 | |
169 | */
170 |
171 | 'secure' => env('SESSION_SECURE_COOKIE'),
172 |
173 | /*
174 | |--------------------------------------------------------------------------
175 | | HTTP Access Only
176 | |--------------------------------------------------------------------------
177 | |
178 | | Setting this value to true will prevent JavaScript from accessing the
179 | | value of the cookie and the cookie will only be accessible through
180 | | the HTTP protocol. You are free to modify this option if needed.
181 | |
182 | */
183 |
184 | 'http_only' => true,
185 |
186 | /*
187 | |--------------------------------------------------------------------------
188 | | Same-Site Cookies
189 | |--------------------------------------------------------------------------
190 | |
191 | | This option determines how your cookies behave when cross-site requests
192 | | take place, and can be used to mitigate CSRF attacks. By default, we
193 | | will set this value to "lax" since this is a secure default value.
194 | |
195 | | Supported: "lax", "strict", "none", null
196 | |
197 | */
198 |
199 | 'same_site' => 'lax',
200 |
201 | ];
202 |
--------------------------------------------------------------------------------
/resources/lang/en/validation.php:
--------------------------------------------------------------------------------
1 | 'The :attribute must be accepted.',
17 | 'accepted_if' => 'The :attribute must be accepted when :other is :value.',
18 | 'active_url' => 'The :attribute is not a valid URL.',
19 | 'after' => 'The :attribute must be a date after :date.',
20 | 'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
21 | 'alpha' => 'The :attribute must only contain letters.',
22 | 'alpha_dash' => 'The :attribute must only contain letters, numbers, dashes and underscores.',
23 | 'alpha_num' => 'The :attribute must only contain letters and numbers.',
24 | 'array' => 'The :attribute must be an array.',
25 | 'before' => 'The :attribute must be a date before :date.',
26 | 'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
27 | 'between' => [
28 | 'numeric' => 'The :attribute must be between :min and :max.',
29 | 'file' => 'The :attribute must be between :min and :max kilobytes.',
30 | 'string' => 'The :attribute must be between :min and :max characters.',
31 | 'array' => 'The :attribute must have between :min and :max items.',
32 | ],
33 | 'boolean' => 'The :attribute field must be true or false.',
34 | 'confirmed' => 'The :attribute confirmation does not match.',
35 | 'current_password' => 'The password is incorrect.',
36 | 'date' => 'The :attribute is not a valid date.',
37 | 'date_equals' => 'The :attribute must be a date equal to :date.',
38 | 'date_format' => 'The :attribute does not match the format :format.',
39 | 'different' => 'The :attribute and :other must be different.',
40 | 'digits' => 'The :attribute must be :digits digits.',
41 | 'digits_between' => 'The :attribute must be between :min and :max digits.',
42 | 'dimensions' => 'The :attribute has invalid image dimensions.',
43 | 'distinct' => 'The :attribute field has a duplicate value.',
44 | 'email' => 'The :attribute must be a valid email address.',
45 | 'ends_with' => 'The :attribute must end with one of the following: :values.',
46 | 'exists' => 'The selected :attribute is invalid.',
47 | 'file' => 'The :attribute must be a file.',
48 | 'filled' => 'The :attribute field must have a value.',
49 | 'gt' => [
50 | 'numeric' => 'The :attribute must be greater than :value.',
51 | 'file' => 'The :attribute must be greater than :value kilobytes.',
52 | 'string' => 'The :attribute must be greater than :value characters.',
53 | 'array' => 'The :attribute must have more than :value items.',
54 | ],
55 | 'gte' => [
56 | 'numeric' => 'The :attribute must be greater than or equal :value.',
57 | 'file' => 'The :attribute must be greater than or equal :value kilobytes.',
58 | 'string' => 'The :attribute must be greater than or equal :value characters.',
59 | 'array' => 'The :attribute must have :value items or more.',
60 | ],
61 | 'image' => 'The :attribute must be an image.',
62 | 'in' => 'The selected :attribute is invalid.',
63 | 'in_array' => 'The :attribute field does not exist in :other.',
64 | 'integer' => 'The :attribute must be an integer.',
65 | 'ip' => 'The :attribute must be a valid IP address.',
66 | 'ipv4' => 'The :attribute must be a valid IPv4 address.',
67 | 'ipv6' => 'The :attribute must be a valid IPv6 address.',
68 | 'json' => 'The :attribute must be a valid JSON string.',
69 | 'lt' => [
70 | 'numeric' => 'The :attribute must be less than :value.',
71 | 'file' => 'The :attribute must be less than :value kilobytes.',
72 | 'string' => 'The :attribute must be less than :value characters.',
73 | 'array' => 'The :attribute must have less than :value items.',
74 | ],
75 | 'lte' => [
76 | 'numeric' => 'The :attribute must be less than or equal :value.',
77 | 'file' => 'The :attribute must be less than or equal :value kilobytes.',
78 | 'string' => 'The :attribute must be less than or equal :value characters.',
79 | 'array' => 'The :attribute must not have more than :value items.',
80 | ],
81 | 'max' => [
82 | 'numeric' => 'The :attribute must not be greater than :max.',
83 | 'file' => 'The :attribute must not be greater than :max kilobytes.',
84 | 'string' => 'The :attribute must not be greater than :max characters.',
85 | 'array' => 'The :attribute must not have more than :max items.',
86 | ],
87 | 'mimes' => 'The :attribute must be a file of type: :values.',
88 | 'mimetypes' => 'The :attribute must be a file of type: :values.',
89 | 'min' => [
90 | 'numeric' => 'The :attribute must be at least :min.',
91 | 'file' => 'The :attribute must be at least :min kilobytes.',
92 | 'string' => 'The :attribute must be at least :min characters.',
93 | 'array' => 'The :attribute must have at least :min items.',
94 | ],
95 | 'multiple_of' => 'The :attribute must be a multiple of :value.',
96 | 'not_in' => 'The selected :attribute is invalid.',
97 | 'not_regex' => 'The :attribute format is invalid.',
98 | 'numeric' => 'The :attribute must be a number.',
99 | 'password' => 'The password is incorrect.',
100 | 'present' => 'The :attribute field must be present.',
101 | 'regex' => 'The :attribute format is invalid.',
102 | 'required' => 'The :attribute field is required.',
103 | 'required_if' => 'The :attribute field is required when :other is :value.',
104 | 'required_unless' => 'The :attribute field is required unless :other is in :values.',
105 | 'required_with' => 'The :attribute field is required when :values is present.',
106 | 'required_with_all' => 'The :attribute field is required when :values are present.',
107 | 'required_without' => 'The :attribute field is required when :values is not present.',
108 | 'required_without_all' => 'The :attribute field is required when none of :values are present.',
109 | 'prohibited' => 'The :attribute field is prohibited.',
110 | 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.',
111 | 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.',
112 | 'same' => 'The :attribute and :other must match.',
113 | 'size' => [
114 | 'numeric' => 'The :attribute must be :size.',
115 | 'file' => 'The :attribute must be :size kilobytes.',
116 | 'string' => 'The :attribute must be :size characters.',
117 | 'array' => 'The :attribute must contain :size items.',
118 | ],
119 | 'starts_with' => 'The :attribute must start with one of the following: :values.',
120 | 'string' => 'The :attribute must be a string.',
121 | 'timezone' => 'The :attribute must be a valid timezone.',
122 | 'unique' => 'The :attribute has already been taken.',
123 | 'uploaded' => 'The :attribute failed to upload.',
124 | 'url' => 'The :attribute must be a valid URL.',
125 | 'uuid' => 'The :attribute must be a valid UUID.',
126 |
127 | /*
128 | |--------------------------------------------------------------------------
129 | | Custom Validation Language Lines
130 | |--------------------------------------------------------------------------
131 | |
132 | | Here you may specify custom validation messages for attributes using the
133 | | convention "attribute.rule" to name the lines. This makes it quick to
134 | | specify a specific custom language line for a given attribute rule.
135 | |
136 | */
137 |
138 | 'custom' => [
139 | 'attribute-name' => [
140 | 'rule-name' => 'custom-message',
141 | ],
142 | ],
143 |
144 | /*
145 | |--------------------------------------------------------------------------
146 | | Custom Validation Attributes
147 | |--------------------------------------------------------------------------
148 | |
149 | | The following language lines are used to swap our attribute placeholder
150 | | with something more reader friendly such as "E-Mail Address" instead
151 | | of "email". This simply helps us make our message more expressive.
152 | |
153 | */
154 |
155 | 'attributes' => [],
156 |
157 | ];
158 |
--------------------------------------------------------------------------------
/config/app.php:
--------------------------------------------------------------------------------
1 | env('APP_NAME', 'Laravel'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Application Environment
21 | |--------------------------------------------------------------------------
22 | |
23 | | This value determines the "environment" your application is currently
24 | | running in. This may determine how you prefer to configure various
25 | | services the application utilizes. Set this in your ".env" file.
26 | |
27 | */
28 |
29 | 'env' => env('APP_ENV', 'production'),
30 |
31 | /*
32 | |--------------------------------------------------------------------------
33 | | Application Debug Mode
34 | |--------------------------------------------------------------------------
35 | |
36 | | When your application is in debug mode, detailed error messages with
37 | | stack traces will be shown on every error that occurs within your
38 | | application. If disabled, a simple generic error page is shown.
39 | |
40 | */
41 |
42 | 'debug' => (bool) env('APP_DEBUG', false),
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Application URL
47 | |--------------------------------------------------------------------------
48 | |
49 | | This URL is used by the console to properly generate URLs when using
50 | | the Artisan command line tool. You should set this to the root of
51 | | your application so that it is used when running Artisan tasks.
52 | |
53 | */
54 |
55 | 'url' => env('APP_URL', 'http://localhost'),
56 |
57 | 'asset_url' => env('ASSET_URL', null),
58 |
59 | /*
60 | |--------------------------------------------------------------------------
61 | | Application Timezone
62 | |--------------------------------------------------------------------------
63 | |
64 | | Here you may specify the default timezone for your application, which
65 | | will be used by the PHP date and date-time functions. We have gone
66 | | ahead and set this to a sensible default for you out of the box.
67 | |
68 | */
69 |
70 | 'timezone' => 'UTC',
71 |
72 | /*
73 | |--------------------------------------------------------------------------
74 | | Application Locale Configuration
75 | |--------------------------------------------------------------------------
76 | |
77 | | The application locale determines the default locale that will be used
78 | | by the translation service provider. You are free to set this value
79 | | to any of the locales which will be supported by the application.
80 | |
81 | */
82 |
83 | 'locale' => 'en',
84 |
85 | /*
86 | |--------------------------------------------------------------------------
87 | | Application Fallback Locale
88 | |--------------------------------------------------------------------------
89 | |
90 | | The fallback locale determines the locale to use when the current one
91 | | is not available. You may change the value to correspond to any of
92 | | the language folders that are provided through your application.
93 | |
94 | */
95 |
96 | 'fallback_locale' => 'en',
97 |
98 | /*
99 | |--------------------------------------------------------------------------
100 | | Faker Locale
101 | |--------------------------------------------------------------------------
102 | |
103 | | This locale will be used by the Faker PHP library when generating fake
104 | | data for your database seeds. For example, this will be used to get
105 | | localized telephone numbers, street address information and more.
106 | |
107 | */
108 |
109 | 'faker_locale' => 'en_US',
110 |
111 | /*
112 | |--------------------------------------------------------------------------
113 | | Encryption Key
114 | |--------------------------------------------------------------------------
115 | |
116 | | This key is used by the Illuminate encrypter service and should be set
117 | | to a random, 32 character string, otherwise these encrypted strings
118 | | will not be safe. Please do this before deploying an application!
119 | |
120 | */
121 |
122 | 'key' => env('APP_KEY'),
123 |
124 | 'cipher' => 'AES-256-CBC',
125 |
126 | /*
127 | |--------------------------------------------------------------------------
128 | | Autoloaded Service Providers
129 | |--------------------------------------------------------------------------
130 | |
131 | | The service providers listed here will be automatically loaded on the
132 | | request to your application. Feel free to add your own services to
133 | | this array to grant expanded functionality to your applications.
134 | |
135 | */
136 |
137 | 'providers' => [
138 |
139 | /*
140 | * Laravel Framework Service Providers...
141 | */
142 | Illuminate\Auth\AuthServiceProvider::class,
143 | Illuminate\Broadcasting\BroadcastServiceProvider::class,
144 | Illuminate\Bus\BusServiceProvider::class,
145 | Illuminate\Cache\CacheServiceProvider::class,
146 | Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
147 | Illuminate\Cookie\CookieServiceProvider::class,
148 | Illuminate\Database\DatabaseServiceProvider::class,
149 | Illuminate\Encryption\EncryptionServiceProvider::class,
150 | Illuminate\Filesystem\FilesystemServiceProvider::class,
151 | Illuminate\Foundation\Providers\FoundationServiceProvider::class,
152 | Illuminate\Hashing\HashServiceProvider::class,
153 | Illuminate\Mail\MailServiceProvider::class,
154 | Illuminate\Notifications\NotificationServiceProvider::class,
155 | Illuminate\Pagination\PaginationServiceProvider::class,
156 | Illuminate\Pipeline\PipelineServiceProvider::class,
157 | Illuminate\Queue\QueueServiceProvider::class,
158 | Illuminate\Redis\RedisServiceProvider::class,
159 | Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
160 | Illuminate\Session\SessionServiceProvider::class,
161 | Illuminate\Translation\TranslationServiceProvider::class,
162 | Illuminate\Validation\ValidationServiceProvider::class,
163 | Illuminate\View\ViewServiceProvider::class,
164 |
165 | /*
166 | * Package Service Providers...
167 | */
168 |
169 | /*
170 | * Application Service Providers...
171 | */
172 | App\Providers\AppServiceProvider::class,
173 | App\Providers\AuthServiceProvider::class,
174 | // App\Providers\BroadcastServiceProvider::class,
175 | App\Providers\EventServiceProvider::class,
176 | App\Providers\RouteServiceProvider::class,
177 |
178 | ],
179 |
180 | /*
181 | |--------------------------------------------------------------------------
182 | | Class Aliases
183 | |--------------------------------------------------------------------------
184 | |
185 | | This array of class aliases will be registered when this application
186 | | is started. However, feel free to register as many as you wish as
187 | | the aliases are "lazy" loaded so they don't hinder performance.
188 | |
189 | */
190 |
191 | 'aliases' => [
192 |
193 | 'App' => Illuminate\Support\Facades\App::class,
194 | 'Arr' => Illuminate\Support\Arr::class,
195 | 'Artisan' => Illuminate\Support\Facades\Artisan::class,
196 | 'Auth' => Illuminate\Support\Facades\Auth::class,
197 | 'Blade' => Illuminate\Support\Facades\Blade::class,
198 | 'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
199 | 'Bus' => Illuminate\Support\Facades\Bus::class,
200 | 'Cache' => Illuminate\Support\Facades\Cache::class,
201 | 'Config' => Illuminate\Support\Facades\Config::class,
202 | 'Cookie' => Illuminate\Support\Facades\Cookie::class,
203 | 'Crypt' => Illuminate\Support\Facades\Crypt::class,
204 | 'Date' => Illuminate\Support\Facades\Date::class,
205 | 'DB' => Illuminate\Support\Facades\DB::class,
206 | 'Eloquent' => Illuminate\Database\Eloquent\Model::class,
207 | 'Event' => Illuminate\Support\Facades\Event::class,
208 | 'File' => Illuminate\Support\Facades\File::class,
209 | 'Gate' => Illuminate\Support\Facades\Gate::class,
210 | 'Hash' => Illuminate\Support\Facades\Hash::class,
211 | 'Http' => Illuminate\Support\Facades\Http::class,
212 | 'Lang' => Illuminate\Support\Facades\Lang::class,
213 | 'Log' => Illuminate\Support\Facades\Log::class,
214 | 'Mail' => Illuminate\Support\Facades\Mail::class,
215 | 'Notification' => Illuminate\Support\Facades\Notification::class,
216 | 'Password' => Illuminate\Support\Facades\Password::class,
217 | 'Queue' => Illuminate\Support\Facades\Queue::class,
218 | 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class,
219 | 'Redirect' => Illuminate\Support\Facades\Redirect::class,
220 | // 'Redis' => Illuminate\Support\Facades\Redis::class,
221 | 'Request' => Illuminate\Support\Facades\Request::class,
222 | 'Response' => Illuminate\Support\Facades\Response::class,
223 | 'Route' => Illuminate\Support\Facades\Route::class,
224 | 'Schema' => Illuminate\Support\Facades\Schema::class,
225 | 'Session' => Illuminate\Support\Facades\Session::class,
226 | 'Storage' => Illuminate\Support\Facades\Storage::class,
227 | 'Str' => Illuminate\Support\Str::class,
228 | 'URL' => Illuminate\Support\Facades\URL::class,
229 | 'Validator' => Illuminate\Support\Facades\Validator::class,
230 | 'View' => Illuminate\Support\Facades\View::class,
231 |
232 | ],
233 |
234 | ];
235 |
--------------------------------------------------------------------------------
/tests/Feature/UserReservationControllerTest.php:
--------------------------------------------------------------------------------
1 | create();
27 |
28 | [$reservation] = Reservation::factory()->for($user)->count(2)->create();
29 |
30 | $image = $reservation->office->images()->create([
31 | 'path' => 'office_image.jpg'
32 | ]);
33 |
34 | $reservation->office()->update(['featured_image_id' => $image->id]);
35 |
36 | Reservation::factory()->count(3)->create();
37 |
38 | $this->actingAs($user);
39 |
40 | $response = $this->getJson('/reservations');
41 |
42 | $response
43 | ->assertJsonStructure(['data', 'meta', 'links'])
44 | ->assertJsonCount(2, 'data')
45 | ->assertJsonStructure(['data' => ['*' => ['id', 'office']]])
46 | ->assertJsonPath('data.0.office.featured_image.id', $image->id);
47 | }
48 |
49 | /**
50 | * @test
51 | */
52 | public function itListsReservationFilteredByDateRange()
53 | {
54 | $user = User::factory()->create();
55 |
56 | $fromDate = '2021-03-03';
57 | $toDate = '2021-04-04';
58 |
59 | // Within the date range
60 | // ...
61 | $reservations = Reservation::factory()->for($user)->createMany([
62 | [
63 | 'start_date' => '2021-03-01',
64 | 'end_date' => '2021-03-15',
65 | ],
66 | [
67 | 'start_date' => '2021-03-25',
68 | 'end_date' => '2021-04-15',
69 | ],
70 | [
71 | 'start_date' => '2021-03-25',
72 | 'end_date' => '2021-03-29',
73 | ],
74 | [
75 | 'start_date' => '2021-03-01',
76 | 'end_date' => '2021-04-15',
77 | ],
78 | ]);
79 |
80 | // Within the range but belongs to a different user
81 | // ...
82 | Reservation::factory()->create([
83 | 'start_date' => '2021-03-25',
84 | 'end_date' => '2021-03-29',
85 | ]);
86 |
87 | // Outside the date range
88 | // ...
89 | Reservation::factory()->for($user)->create([
90 | 'start_date' => '2021-02-25',
91 | 'end_date' => '2021-03-01',
92 | ]);
93 |
94 | Reservation::factory()->for($user)->create([
95 | 'start_date' => '2021-05-01',
96 | 'end_date' => '2021-05-01',
97 | ]);
98 |
99 | $this->actingAs($user);
100 |
101 | $response = $this->getJson('/reservations?'.http_build_query([
102 | 'from_date' => $fromDate,
103 | 'to_date' => $toDate,
104 | ]));
105 |
106 | $response
107 | ->assertJsonCount(4, 'data');
108 |
109 | $this->assertEquals($reservations->pluck('id')->toArray(), collect($response->json('data'))->pluck('id')->toArray());
110 | }
111 |
112 | /**
113 | * @test
114 | */
115 | public function itFiltersResultsByStatus()
116 | {
117 | $user = User::factory()->create();
118 |
119 | $reservation = Reservation::factory()->for($user)->create([
120 | 'status' => Reservation::STATUS_ACTIVE
121 | ]);
122 |
123 | $reservation2 = Reservation::factory()->for($user)->cancelled()->create();
124 |
125 | $this->actingAs($user);
126 |
127 | $response = $this->getJson('/reservations?'.http_build_query([
128 | 'status' => Reservation::STATUS_ACTIVE,
129 | ]));
130 |
131 | $response
132 | ->assertJsonCount(1, 'data')
133 | ->assertJsonPath('data.0.id', $reservation->id);
134 | }
135 |
136 | /**
137 | * @test
138 | */
139 | public function itFiltersResultsByOffice()
140 | {
141 | $user = User::factory()->create();
142 |
143 | $office = Office::factory()->create();
144 |
145 | $reservation = Reservation::factory()->for($office)->for($user)->create();
146 |
147 | $reservation2 = Reservation::factory()->for($user)->create();
148 |
149 | $this->actingAs($user);
150 |
151 | $response = $this->getJson('/reservations?'.http_build_query([
152 | 'office_id' => $office->id,
153 | ]));
154 |
155 | $response
156 | ->assertJsonCount(1, 'data')
157 | ->assertJsonPath('data.0.id', $reservation->id);
158 | }
159 |
160 | /**
161 | * @test
162 | */
163 | public function itMakesReservations()
164 | {
165 | $user = User::factory()->create();
166 |
167 | $office = Office::factory()->create([
168 | 'price_per_day' => 1_000,
169 | 'monthly_discount' => 10,
170 | ]);
171 |
172 | $this->actingAs($user);
173 |
174 | $response = $this->postJson('/reservations', [
175 | 'office_id' => $office->id,
176 | 'start_date' => now()->addDay(),
177 | 'end_date' => now()->addDays(40),
178 | ]);
179 |
180 | $response->assertCreated();
181 |
182 | $response->assertJsonPath('data.price', 36000)
183 | ->assertJsonPath('data.user_id', $user->id)
184 | ->assertJsonPath('data.office_id', $office->id)
185 | ->assertJsonPath('data.status', Reservation::STATUS_ACTIVE);
186 | }
187 |
188 | /**
189 | * @test
190 | */
191 | public function itCannotMakeReservationOnNonExistingOffice()
192 | {
193 | $user = User::factory()->create();
194 |
195 | $this->actingAs($user);
196 |
197 | $response = $this->postJson('/reservations', [
198 | 'office_id' => 10000,
199 | 'start_date' => now()->addDay(),
200 | 'end_date' => now()->addDays(41),
201 | ]);
202 |
203 | $response->assertUnprocessable()
204 | ->assertJsonValidationErrors(['office_id' => 'Invalid office_id']);
205 | }
206 |
207 | /**
208 | * @test
209 | */
210 | public function itCannotMakeReservationOnOfficeThatBelongsToTheUser()
211 | {
212 | $user = User::factory()->create();
213 |
214 | $office = Office::factory()->for($user)->create();
215 |
216 | $this->actingAs($user);
217 |
218 | $response = $this->postJson('/reservations', [
219 | 'office_id' => $office->id,
220 | 'start_date' => now()->addDay(),
221 | 'end_date' => now()->addDays(41),
222 | ]);
223 |
224 | $response->assertUnprocessable()
225 | ->assertJsonValidationErrors(['office_id' => 'You cannot make a reservation on your own office']);
226 | }
227 |
228 | /**
229 | * @test
230 | */
231 | public function itCannotMakeReservationOnOfficeThatIsPendingOrHidden()
232 | {
233 | $user = User::factory()->create();
234 |
235 | $office = Office::factory()->create([
236 | 'approval_status' => Office::APPROVAL_PENDING
237 | ]);
238 |
239 | $office2 = Office::factory()->create([
240 | 'hidden' => true
241 | ]);
242 |
243 | $this->actingAs($user);
244 |
245 | $response = $this->postJson('/reservations', [
246 | 'office_id' => $office->id,
247 | 'start_date' => now()->addDay(),
248 | 'end_date' => now()->addDays(41),
249 | ]);
250 |
251 | $response2 = $this->postJson('/reservations', [
252 | 'office_id' => $office2->id,
253 | 'start_date' => now()->addDay(),
254 | 'end_date' => now()->addDays(41),
255 | ]);
256 |
257 | $response->assertUnprocessable()
258 | ->assertJsonValidationErrors(['office_id' => 'You cannot make a reservation on a hidden office']);
259 |
260 | $response2->assertUnprocessable()
261 | ->assertJsonValidationErrors(['office_id' => 'You cannot make a reservation on a hidden office']);
262 | }
263 |
264 | /**
265 | * @test
266 | */
267 | public function itCannotMakeReservationLessThan2Days()
268 | {
269 | $user = User::factory()->create();
270 |
271 | $office = Office::factory()->create();
272 |
273 | $this->actingAs($user);
274 |
275 | $response = $this->postJson('/reservations', [
276 | 'office_id' => $office->id,
277 | 'start_date' => now()->addDay(),
278 | 'end_date' => now()->addDay(),
279 | ]);
280 |
281 | $response->assertUnprocessable()
282 | ->assertJsonValidationErrors(['end_date' => 'The end date must be a date after start date.']);
283 | }
284 |
285 | /**
286 | * @test
287 | */
288 | public function itCannotMakeReservationOnSameDay()
289 | {
290 | $user = User::factory()->create();
291 |
292 | $office = Office::factory()->create();
293 |
294 | $this->actingAs($user);
295 |
296 | $response = $this->postJson('/reservations', [
297 | 'office_id' => $office->id,
298 | 'start_date' => now()->toDateString(),
299 | 'end_date' => now()->addDays(3)->toDateString(),
300 | ]);
301 |
302 | $response->assertUnprocessable()
303 | ->assertJsonValidationErrors(['start_date' => 'The start date must be a date after today.']);
304 | }
305 |
306 | /**
307 | * @test
308 | */
309 | public function itMakeReservationFor2Days()
310 | {
311 | $user = User::factory()->create();
312 |
313 | $office = Office::factory()->create();
314 |
315 | $this->actingAs($user);
316 |
317 | $response = $this->postJson('/reservations', [
318 | 'office_id' => $office->id,
319 | 'start_date' => now()->addDay(),
320 | 'end_date' => now()->addDays(2),
321 | ]);
322 |
323 | $response->assertCreated();
324 | }
325 |
326 | /**
327 | * @test
328 | */
329 | public function itCannotMakeReservationThatsConflicting()
330 | {
331 | $user = User::factory()->create();
332 |
333 | $fromDate = now()->addDays(2)->toDateString();
334 | $toDate = now()->addDay(15)->toDateString();
335 |
336 | $office = Office::factory()->create();
337 |
338 | Reservation::factory()->for($office)->create([
339 | 'start_date' => now()->addDay(2),
340 | 'end_date' => $toDate,
341 | ]);
342 |
343 | $this->actingAs($user);
344 |
345 | $response = $this->postJson('/reservations', [
346 | 'office_id' => $office->id,
347 | 'start_date' => $fromDate,
348 | 'end_date' => $toDate,
349 | ]);
350 |
351 | $response->assertUnprocessable()
352 | ->assertJsonValidationErrors(['office_id' => 'You cannot make a reservation during this time']);
353 | }
354 |
355 | /**
356 | * @test
357 | */
358 | public function itSendsNotificationsOnNewReservations()
359 | {
360 | Notification::fake();
361 |
362 | $user = User::factory()->create();
363 |
364 | $office = Office::factory()->create();
365 |
366 | $this->actingAs($user);
367 |
368 | $response = $this->postJson('/reservations', [
369 | 'office_id' => $office->id,
370 | 'start_date' => now()->addDay(),
371 | 'end_date' => now()->addDays(2),
372 | ]);
373 |
374 | Notification::assertSentTo($user, NewUserReservation::class);
375 | Notification::assertSentTo($office->user, NewHostReservation::class);
376 |
377 | $response->assertCreated();
378 | }
379 | }
380 |
--------------------------------------------------------------------------------
/tests/Feature/OfficeControllerTest.php:
--------------------------------------------------------------------------------
1 | create();
28 | $tags = Tag::factory(2)->create();
29 | $tags2 = Tag::factory(2)->create();
30 |
31 | Office::factory(30)->for($user)->create();
32 |
33 | Office::factory()->for($user)->hasAttached($tags)->create();
34 | Office::factory()->hasAttached($tags2)->create();
35 |
36 | $response = $this->get('/offices');
37 |
38 | $response->assertOk()
39 | ->assertJsonStructure(['data', 'meta', 'links'])
40 | ->assertJsonCount(20, 'data')
41 | ->assertJsonStructure(['data' => ['*' => ['id', 'title']]]);
42 | }
43 |
44 | /**
45 | * @test
46 | */
47 | public function itOnlyListsOfficesThatAreNotHiddenAndApproved()
48 | {
49 | Office::factory(3)->create();
50 |
51 | Office::factory()->hidden()->create();
52 | Office::factory()->pending()->create();
53 |
54 | $response = $this->get('/offices');
55 |
56 | $response->assertOk()
57 | ->assertJsonCount(3, 'data');
58 | }
59 |
60 | /**
61 | * @test
62 | */
63 | public function itListsOfficesIncludingHiddenAndUnApprovedIfFilteringForTheCurrentLoggedInUser()
64 | {
65 | $user = User::factory()->create();
66 |
67 | Office::factory(3)->for($user)->create();
68 |
69 | Office::factory()->hidden()->for($user)->create();
70 | Office::factory()->pending()->for($user)->create();
71 |
72 | $this->actingAs($user);
73 |
74 | $response = $this->get('/offices?user_id='.$user->id);
75 |
76 | $response->assertOk()
77 | ->assertJsonCount(5, 'data');
78 | }
79 |
80 | /**
81 | * @test
82 | */
83 | public function itFiltersByUserId()
84 | {
85 | Office::factory(3)->create();
86 |
87 | $host = User::factory()->create();
88 | $office = Office::factory()->for($host)->create();
89 |
90 | $response = $this->get(
91 | '/offices?user_id='.$host->id
92 | );
93 |
94 | $response->assertOk()
95 | ->assertJsonCount(1, 'data')
96 | ->assertJsonPath('data.0.id', $office->id);
97 | }
98 |
99 | /**
100 | * @test
101 | */
102 | public function itFiltersByVisitorId()
103 | {
104 | Office::factory(3)->create();
105 |
106 | $user = User::factory()->create();
107 | $office = Office::factory()->create();
108 |
109 | Reservation::factory()->for(Office::factory())->create();
110 | Reservation::factory()->for($office)->for($user)->create();
111 |
112 | $response = $this->get(
113 | '/offices?visitor_id='.$user->id
114 | );
115 |
116 | $response->assertOk()
117 | ->assertJsonCount(1, 'data')
118 | ->assertJsonPath('data.0.id', $office->id);
119 | }
120 |
121 | /**
122 | * @test
123 | */
124 | public function itFiltersByTags()
125 | {
126 | $tags = Tag::factory(2)->create();
127 |
128 | $office = Office::factory()->hasAttached($tags)->create();
129 | Office::factory()->hasAttached($tags->first())->create();
130 | Office::factory()->create();
131 |
132 | $response = $this->get(
133 | '/offices?'.http_build_query([
134 | 'tags' => $tags->pluck('id')->toArray()
135 | ])
136 | );
137 |
138 | $response->assertOk()
139 | ->assertJsonCount(1, 'data')
140 | ->assertJsonPath('data.0.id', $office->id);
141 | }
142 |
143 | /**
144 | * @test
145 | */
146 | public function itIncludesImagesTagsAndUser()
147 | {
148 | $user = User::factory()->create();
149 | Office::factory()->for($user)->hasTags(1)->hasImages(1)->create();
150 |
151 | $response = $this->get('/offices');
152 |
153 | $response->assertOk()
154 | ->assertJsonCount(1, 'data.0.tags')
155 | ->assertJsonCount(1, 'data.0.images')
156 | ->assertJsonPath('data.0.user.id', $user->id);
157 | }
158 |
159 |
160 | /**
161 | * @test
162 | */
163 | public function itReturnsTheNumberOfActiveReservations()
164 | {
165 | $office = Office::factory()->create();
166 |
167 | Reservation::factory()->for($office)->create();
168 | Reservation::factory()->for($office)->cancelled()->create();
169 |
170 | $response = $this->get('/offices');
171 |
172 | $response->assertOk()
173 | ->assertJsonPath('data.0.reservations_count', 1);
174 | }
175 |
176 | /**
177 | * @test
178 | */
179 | public function itOrdersByDistanceWhenCoordinatesAreProvided()
180 | {
181 | Office::factory()->create([
182 | 'lat' => '39.74051727562952',
183 | 'lng' => '-8.770375324893696',
184 | 'title' => 'Leiria'
185 | ]);
186 |
187 | Office::factory()->create([
188 | 'lat' => '39.07753883078113',
189 | 'lng' => '-9.281266331143293',
190 | 'title' => 'Torres Vedras'
191 | ]);
192 |
193 | $response = $this->get('/offices?lat=38.720661384644046&lng=-9.16044783453807');
194 |
195 | $response->assertOk()
196 | ->assertJsonPath('data.0.title', 'Torres Vedras')
197 | ->assertJsonPath('data.1.title', 'Leiria');
198 |
199 | $response = $this->get('/offices');
200 |
201 | $response->assertOk()
202 | ->assertJsonPath('data.0.title', 'Leiria')
203 | ->assertJsonPath('data.1.title', 'Torres Vedras');
204 | }
205 |
206 | /**
207 | * @test
208 | */
209 | public function itShowsTheOffice()
210 | {
211 | $user = User::factory()->create();
212 |
213 | $office = Office::factory()->for($user)->hasTags(1)->hasImages(1)->create();
214 |
215 | Reservation::factory()->for($office)->create();
216 | Reservation::factory()->for($office)->cancelled()->create();
217 |
218 | $response = $this->get('/offices/'.$office->id);
219 |
220 | $response->assertOk()
221 | ->assertJsonPath('data.reservations_count', 1)
222 | ->assertJsonCount(1, 'data.tags')
223 | ->assertJsonCount(1, 'data.images')
224 | ->assertJsonPath('data.user.id', $user->id);
225 | }
226 |
227 | /**
228 | * @test
229 | */
230 | public function itCreatesAnOffice()
231 | {
232 | Notification::fake();
233 |
234 | $admin = User::factory()->create(['is_admin' => true]);
235 |
236 | $user = User::factory()->create();
237 | $tags = Tag::factory(2)->create();
238 |
239 | Sanctum::actingAs($user, ['*']);
240 |
241 | $response = $this->postJson('/offices', Office::factory()->raw([
242 | 'tags' => $tags->pluck('id')->toArray()
243 | ]));
244 |
245 | $response->assertCreated()
246 | ->assertJsonPath('data.approval_status', Office::APPROVAL_PENDING)
247 | ->assertJsonPath('data.reservations_count', 0)
248 | ->assertJsonPath('data.user.id', $user->id)
249 | ->assertJsonCount(2, 'data.tags');
250 |
251 | $this->assertDatabaseHas('offices', [
252 | 'id' => $response->json('data.id')
253 | ]);
254 |
255 | Notification::assertSentTo($admin, OfficePendingApproval::class);
256 | }
257 |
258 | /**
259 | * @test
260 | */
261 | public function itDoesntAllowCreatingIfScopeIsNotProvided()
262 | {
263 | $user = User::factory()->create();
264 |
265 | Sanctum::actingAs($user, []);
266 |
267 | $response = $this->postJson('/offices');
268 |
269 | $response->assertForbidden();
270 | }
271 |
272 | /**
273 | * @test
274 | */
275 | public function itAllowsCreatingIfScopeIsProvided()
276 | {
277 | $user = User::factory()->create();
278 |
279 | Sanctum::actingAs($user, ['office.create']);
280 |
281 | $response = $this->postJson('/offices');
282 |
283 | $this->assertNotEquals(Response::HTTP_FORBIDDEN, $response->status());
284 | }
285 |
286 | /**
287 | * @test
288 | */
289 | public function itUpdatesAnOffice()
290 | {
291 | $user = User::factory()->create();
292 | $tags = Tag::factory(3)->create();
293 | $office = Office::factory()->for($user)->create();
294 |
295 | $office->tags()->attach($tags);
296 |
297 | $this->actingAs($user);
298 |
299 | $anotherTag = Tag::factory()->create();
300 |
301 | $response = $this->putJson('/offices/'.$office->id, [
302 | 'title' => 'Amazing Office',
303 | 'tags' => [$tags[0]->id, $anotherTag->id]
304 | ]);
305 |
306 | $response->assertOk()
307 | ->assertJsonCount(2, 'data.tags')
308 | ->assertJsonPath('data.tags.0.id', $tags[0]->id)
309 | ->assertJsonPath('data.tags.1.id', $anotherTag->id)
310 | ->assertJsonPath('data.title', 'Amazing Office');
311 | }
312 |
313 | /**
314 | * @test
315 | */
316 | public function itDoesntUpdateOfficeThatDoesntBelongToUser()
317 | {
318 | $user = User::factory()->create();
319 | $anotherUser = User::factory()->create();
320 | $office = Office::factory()->for($anotherUser)->create();
321 |
322 | $this->actingAs($user);
323 |
324 | $response = $this->putJson('/offices/'.$office->id, [
325 | 'title' => 'Amazing Office'
326 | ]);
327 |
328 | $response->assertStatus(Response::HTTP_FORBIDDEN);
329 | }
330 |
331 | /**
332 | * @test
333 | */
334 | public function itMarksTheOfficeAsPendingIfDirty()
335 | {
336 | $admin = User::factory()->create(['is_admin' => true]);
337 |
338 | Notification::fake();
339 |
340 | $user = User::factory()->create();
341 | $office = Office::factory()->for($user)->create();
342 |
343 | $this->actingAs($user);
344 |
345 | $response = $this->putJson('/offices/'.$office->id, [
346 | 'lat' => 40.74051727562952
347 | ]);
348 |
349 | $response->assertOk();
350 |
351 | $this->assertDatabaseHas('offices', [
352 | 'id' => $office->id,
353 | 'approval_status' => Office::APPROVAL_PENDING,
354 | ]);
355 |
356 | Notification::assertSentTo($admin, OfficePendingApproval::class);
357 | }
358 |
359 | /**
360 | * @test
361 | */
362 | public function itUpdatedTheFeaturedImageOfAnOffice()
363 | {
364 | $user = User::factory()->create();
365 | $office = Office::factory()->for($user)->create();
366 |
367 | $image = $office->images()->create([
368 | 'path' => 'image.jpg'
369 | ]);
370 |
371 | $this->actingAs($user);
372 |
373 | $response = $this->putJson('/offices/'.$office->id, [
374 | 'featured_image_id' => $image->id,
375 | ]);
376 |
377 | $response->assertOk()
378 | ->assertJsonPath('data.featured_image_id', $image->id);
379 | }
380 |
381 | /**
382 | * @test
383 | */
384 | public function itDoesntUpdateFeaturedImageThatBelongsToAnotherOffice()
385 | {
386 | $user = User::factory()->create();
387 | $office = Office::factory()->for($user)->create();
388 | $office2 = Office::factory()->for($user)->create();
389 |
390 | $image = $office2->images()->create([
391 | 'path' => 'image.jpg'
392 | ]);
393 |
394 | $this->actingAs($user);
395 |
396 | $response = $this->putJson('/offices/'.$office->id, [
397 | 'featured_image_id' => $image->id,
398 | ]);
399 |
400 | $response->assertUnprocessable()->assertInvalid('featured_image_id');
401 | }
402 |
403 | /**
404 | * @test
405 | */
406 | public function itCanDeleteOffices()
407 | {
408 | Storage::put('/office_image.jpg', 'empty');
409 |
410 | $user = User::factory()->create();
411 | $office = Office::factory()->for($user)->create();
412 |
413 | $image = $office->images()->create([
414 | 'path' => 'office_image.jpg'
415 | ]);
416 |
417 | $this->actingAs($user);
418 |
419 | $response = $this->deleteJson('/offices/'.$office->id);
420 |
421 | $response->assertOk();
422 |
423 | $this->assertSoftDeleted($office);
424 |
425 | $this->assertModelMissing($image);
426 |
427 | Storage::assertMissing('office_image.jpg');
428 | }
429 |
430 | /**
431 | * @test
432 | */
433 | public function itCannotDeleteAnOfficeThatHasReservations()
434 | {
435 | $user = User::factory()->create();
436 | $office = Office::factory()->for($user)->create();
437 |
438 | Reservation::factory(3)->for($office)->create();
439 |
440 | $this->actingAs($user);
441 |
442 | $response = $this->deleteJson('/offices/'.$office->id);
443 |
444 | $response->assertUnprocessable();
445 |
446 | $this->assertNotSoftDeleted($office);
447 | }
448 | }
449 |
--------------------------------------------------------------------------------
/resources/views/welcome.blade.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Laravel
8 |
9 |
10 |
11 |
12 |
13 |
16 |
17 |
22 |
23 |
24 |
25 | @if (Route::has('login'))
26 |
27 | @auth
28 |
Home
29 | @else
30 |
Log in
31 |
32 | @if (Route::has('register'))
33 |
Register
34 | @endif
35 | @endauth
36 |
37 | @endif
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
55 |
56 |
57 |
58 | Laravel has wonderful, thorough documentation covering every aspect of the framework. Whether you are new to the framework or have previous experience with Laravel, we recommend reading all of the documentation from beginning to end.
59 |
60 |
61 |
62 |
63 |
64 |
68 |
69 |
70 |
71 | Laracasts offers thousands of video tutorials on Laravel, PHP, and JavaScript development. Check them out, see for yourself, and massively level up your development skills in the process.
72 |
73 |
74 |
75 |
76 |
77 |
81 |
82 |
83 |
84 | Laravel News is a community driven portal and newsletter aggregating all of the latest and most important news in the Laravel ecosystem, including new package releases and tutorials.
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
Vibrant Ecosystem
93 |
94 |
95 |
96 |
97 | Laravel's robust library of first-party tools and libraries, such as
Forge ,
Vapor ,
Nova , and
Envoyer help you take your projects to the next level. Pair them with powerful open source libraries like
Cashier ,
Dusk ,
Echo ,
Horizon ,
Sanctum ,
Telescope , and more.
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
124 |
125 |
126 | Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }})
127 |
128 |
129 |
130 |
131 |
132 |
133 |
--------------------------------------------------------------------------------