Permalink
Browse files

Auth notes

  • Loading branch information...
susanBuck committed Dec 6, 2018
1 parent ad658c2 commit e5502af76656d68a6f75e9b46aa1ac6f4306e2fc
Showing with 79 additions and 53 deletions.
  1. +4 −1 README.md
  2. +42 −19 laravel/auth-foobooks.md
  3. +26 −25 laravel/auth-setup.md
  4. +7 −8 laravel/auth-usage.md
@@ -106,6 +106,9 @@ If you have a suggestion regarding a particular topic (correction, typo, etc.),
+ [Relationships: One to Many](/laravel/db-one-to-many.md)
+ [Foobooks: One to Many](/laravel/foobooks-week-13a.md)
+ [Relationships: Many to Many](/laravel/db-many-to-many.md)
+ [Foobooks: Many to Many](/laravel/foobooks-week-13b.md)
+ [Foobooks: Many to Many](/laravel/foobooks-week-13b.md)
+ [Auth setup](/laravel/auth-setup.md)
+ [Auth usage](/laravel/auth-usage.md)
+ [Auth in Foobooks](/laravel/auth-foobooks.md)
+ Extras
+ [Eloquent vs. Query Builder](laravel/db-eloquent-vs-qb.md)
@@ -88,42 +88,65 @@ public function books()
## Your Books
Setup complete! Now let's make it so that when a user is logged in they only see *their* books.
Update the `index` method in the BookController like so:
To do this, update the first two lines of your index method as shown:
```php
public function index(Request $request)
{
$user = $request->user();
# Note: We're getting the user from the request, but you can also get it like this:
//$user = Auth::user();
# Approach 1)
//$books = Book::where('user_id', '=', $user->id)->orderBy('title')->get();
# Approach 2) Take advantage of Model relationships
$books = $user->books()->orderBy('title')->get();
# Query the existing Collection to get the last 3 books added
# ** NEW LINE ** Get the user object
$user = $request->user();
# ** UPDATED LINE ** Edit the books query so it's fetching the books via the user object
$books = $user->books()->orderBy('title')->get();
# Approach 1 - Query the database
# $newBooks = Book::latest()->limit(3)->get();
# Approach 2 - Query the collection (more efficient)
$newBooks = $books->sortByDesc('created_at')->take(3);
return view('books.index')->with([
'books' => $books,
'newBooks' => $newBooks,
'books' => $books,
'newBooks' => $newBooks
]);
}
```
### View modifications
In addition to the above changes, we also made the modifications to the book index view:
In addition to the above changes, you should also make the following modifications to the book index view:
+ Update the heading on the book index from *All Books* to *Your Books*.
+ Only show the new books call-out if there are new books.
+ If there are no books to show, link to the page to add a new book.
Study [/resources/book/index.blade.php](https://github.com/susanBuck/foobooks/blob/master/resources/views/book/index.blade.php) to see the details of these changes.
```php
@section('content')
@if($newBooks->count() > 0)
<section id='newBooks'>
<h2>Recently added books</h2>
<ul>
@foreach($newBooks as $book)
<li>{{ $book->title }}</li>
@endforeach
</ul>
</section>
@endif
<section id='allBooks'>
<h2>Your books</h2>
@if($books->count() == 0)
<p>You don't have any books yet; would you like to <a href='/books/create'>add one?</a></p>
@else
@foreach($books as $book)
@include('books._book')
@endforeach
@endif
</section>
@endsection
```
### Test it out
+ Login as Jill and you should see all the books (since they're all seeded to her)
+ Login as Jamal to see the &ldquo;blank slate&rdquo; page with no books to show.
@@ -42,13 +42,14 @@ If you open `database/migrations/2014_10_12_000000_create_users_table.php` you c
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
```
@@ -69,45 +70,44 @@ Next, open `/app/Http/Controllers/Auth/` and note the various existing controlle
+ `LoginController.php`
+ `RegisterController.php`
+ `ResetPasswordController.php`
+ `VerificationController.php`
## php artisan make:auth
Now that you've seen the existing auth-related files that Laravel ships with, the next step is to run the command `php artisan make:auth`. This will make some modifications and additions necessary for authorization.
Below is an example output of `git status` after running this command, to highlight the changes it produces:
```xml
/Applications/MAMP/htdocs/foobooks $ php artisan make:auth
/Applications/MAMP/htdocs/foobooks (master) $ php artisan make:auth
Authentication scaffolding generated successfully.
/Applications/MAMP/htdocs/foobooks $ git status
/Applications/MAMP/htdocs/foobooks (master) ! $ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: routes/web.php
modified: routes/web.php
Untracked files:
(use "git add <file>..." to include in what will be committed)
app/Http/Controllers/HomeController.php
resources/views/auth/
resources/views/home.blade.php
resources/views/layouts/app.blade.php
no changes added to commit (use "git add" and/or "git commit -a")
app/Http/Controllers/HomeController.php
resources/views/auth/
resources/views/home.blade.php
resources/views/layouts/app.blade.php
```
## Routes
One of the changes made by `make:auth` is it edits your routes file adding two lines at the bottom.
One of the changes made by `make:auth` is it edits your `routes/web.php` file adding two lines at the bottom.
The first new line is this one:
```php
Auth::routes();
```
This single line sets up 10 different routes for your application, including:
This single line adds 10 new routes for your application, including:
+ `/login` (GET & POST)
+ `/logout` (GET)
@@ -116,7 +116,7 @@ This single line sets up 10 different routes for your application, including:
+ `/password/reset/{token}` (GET)
+ `/register` (GET & POST)
To see all these routes, run `php artisan route:list`. The following screenshot shows the relevant links highlighted:
To see all these routes, run `php artisan route:list`. The following screenshot shows the relevant routes, marked by a green dot:
<img src='http://making-the-internet.s3.amazonaws.com/laravel-auth-routes@2x.png' style='max-width:1180px;' alt=''>
@@ -132,6 +132,7 @@ To make this customization, you'll edit the following files:
+ `app/Http/Controllers/Auth/LoginController.php`
+ `app/Http/Controllers/Auth/RegisterController.php`
+ `app/Http/Controllers/Auth/ResetPasswordController.php`
+ `app/Http/Controllers/Auth/VerificationController.php`
In these files, find this line:
```php
@@ -164,7 +165,7 @@ Route::get('/home', 'HomeController@index')->name('home');
## Views
When `php artisan make:auth` is invoked to create the auth routes, this command also created some new auth-related view files which you'll want to customize to match your application.
When you invoked `php artisan make:auth` create the auth routes, this command also created some new auth-related view files which you'll want to customize to match your application.
To begin, open `resources/views/auth/login.blade.php`&mdash; we want to adapt this view to match the patterns we've been using in our other views.
@@ -196,11 +197,11 @@ Note that the following essential pieces are kept in tact:
<label for='email'>E-Mail Address</label>
<input id='email' type='email' name='email' value='{{ old('email') }}' required autofocus>
@include('modules.error-field', ['field' => 'email'])
@include('modules.field-error', ['field' => 'email'])
<label for='password'>Password</label>
<input id='password' type='password' name='password' required>
@include('modules.error-field', ['field' => 'password'])
@include('modules.field-error', ['field' => 'password'])
<label>
<input type='checkbox' name='remember' {{ old('remember') ? 'checked' : '' }}> Remember Me
@@ -230,15 +231,15 @@ Similarly, we can amend `resources/views/auth/register.blade.php` to this:
<label for='name'>Name</label>
<input id='name' type='text' name='name' value='{{ old('name') }}' required autofocus>
@include('modules.error-field', ['field' => 'name'])
@include('modules.field-error', ['field' => 'name'])
<label for='email'>E-Mail Address</label>
<input id='email' type='email' name='email' value='{{ old('email') }}' required>
@include('modules.error-field', ['field' => 'email'])
@include('modules.field-error', ['field' => 'email'])
<label for='password'>Password (min: 6)</label>
<input id='password' type='password' name='password' required>
@include('modules.error-field', ['field' => 'password'])
@include('modules.field-error', ['field' => 'password'])
<label for='password-confirm'>Confirm Password</label>
<input id='password-confirm' type='password' name='password_confirmation' required>
@@ -28,9 +28,8 @@ You'll recall that our navigation links are defined in `/config/app.php`:
```php
'nav' => [
'/books' => 'Books',
'/books/create' => 'New Book',
'/books/create' => 'Add a book',
'/books/search' => 'Search',
'/trivia' => 'Trivia',
'/practice' => 'Practice',
'/about' => 'About',
'/contact' => 'Contact',
@@ -52,7 +51,6 @@ We're going to split this into two separate configs, one for when the visitor is
'/books' => 'Books',
'/books/create' => 'New Book',
'/books/search' => 'Search',
'/trivia' => 'Trivia',
'/practice' => 'Practice',
'/about' => 'About',
'/contact' => 'Contact',
@@ -92,11 +90,12 @@ Laravel ships with a default middleware file for authentication (`Illuminate\Aut
To understand how this middleware is used, open `/app/Http/Kernel.php` and note that it's part of the `$routeMiddleWare` array with the key `auth`:
```php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
```

0 comments on commit e5502af

Please sign in to comment.