OLD Laravel Flashcards

Learn Laravel inside-out

1
Q

How does Laravel allow you to define your database structure?

A

With code-driven migrations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the main advantage to using database migrations?

A

Any new environment can be brought up from bare database to your app’s schema immediately.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Database migrations are always run in what order

A

chronological

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What two methods are defined in a typical database migration file?

A

up() and down().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you create a new migration that creates a new table?

A

php artisan make:migration create_users_table –create=users

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you create a new migration that modifies an existing table?

A

php artisan make:migration add_votes_to_users_table –table=users

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What two flags can you optionally pass to the Artisan make:migration command?

A

–create=table_name pre-fills the migration to create a new table named table_name, and

–table=table_name pre-fills the migration to modify an existing table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What command runs all outstanding migrations?

A

php artisan migrate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the “php artisan migrate” command do?

A

Runs all outstanding migrations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Migrations depend on the what facade and its methods?

A

Illuminate\Support\Facades\Schema

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Where are you most likely to use the “Schema” facade?

A

In database migrations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In instance of what class is passed into the closure passed into the Schema facade during a migration?

A

Illuminate\Database\Schema\Blueprint

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Where are you most likely to see the “Blueprint” class used?

A

In database migrations - passed into the closure given to Schema.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Reiterate the boilerplate code that’s added to the up() method in a new database migration.

A
public function up()
{
    Schema::table('tour_types', function (Blueprint $table) {
        //
    });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you modify an existing column during a database migration?

A

Write the same code that would create the column as if it were new, and then append a call to the change() method after it.

For example, if you had an existing column named “name” that has a length of 255 and want to change its length to 100…

Schema::table(‘users’, function (Blueprint $table) {
$table->string(‘name’, 100)->change();
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Where are you most likely to see this code?

Schema::table('tour_types', function (Blueprint $table) {
    //
});
A

In a database migration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Write the following code for the up() method of a database migration:
Change the ‘deleted_at’ column of the ‘contacts’ table to be nullable.

A

Schema::table(‘contacts’, function (Blueprint $table) {
$table->string(‘deleted_at’)->nullable()->change();
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Write the following code for the up() method of a database migration:
Rename a column.

A

Schema::table(‘contacts’, function (Blueprint $table) {
$table->renameColumn(‘old_name’, ‘new_name’);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Write the following code for the up() method of a database migration:
Drop a column.

A

Schema::table(‘contacts’, function (Blueprint $table) {
$table->dropColumn(‘votes’);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Write the following code for the up() method of a database migration:
Drop multiple columns from the same table.

A

Schema::table(‘contacts’, function (Blueprint $table) {
$table->dropColumn([‘votes’, ‘avatar’, ‘location’]);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Write the following code for the up() method of a database migration:
Add a foreign key.

A

Schema::table(‘contacts’, function (Blueprint $table) {
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What can the DB facade be used for?

A

For both query builder chaining and for raw SQL queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What four general categories can you split query builder methods into?

A
  • Constraining methods,
  • modifying methods,
  • conditional methods, and
  • ending/returning methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

A DB facade query returns an instance of what collection?

A

Illuminate\Support\Collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

An Eloquent query returns an instance of what collection?

A

Illuminate\Database\Eloquent\Collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the basic collection class?

A

Illuminate\Support\Collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Which class extends the basic collection with a few Eloquent-specific methods?

A

Illuminate\Database\Eloquent\Collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What method do you use in QueryBuilder when specifying what columns you want to query?

A

select() or addSelect():

agent = Agency::select(‘name’, ‘country’)

 - >addSelect('id')
 - >get();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

In QueryBuilder, how do you selects only rows where the selected data is unique compared to the other rows in the returned data?

A

Using distinct(), eg:

Page::select(‘view’)->distinct->get();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

In QueryBuilder, how do you conditionally limit the scope of the returned data?

A

Using where(), eg:

Page::where(‘view’, ‘default’)->get();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

In QueryBuilder, how do you conditionally limit the scope of the returned data using several conditions?

A

Chain together multiples calls to where() for an AND situation, or use orWhere() to create an OR situation.

May also use an array (but not as nice IMHO)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

In QueryBuilder, how to return only rows where a particular column value is between two given values?

A

Use whereBetween() - which is inclusive of the bounds.

$mediumDrinks = DB::table(‘shoes’)

- >whereBetween('size', [6, 12])
- >get();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

In QueryBuilder, how to return only rows where a particular column value is NOT between two given values?

A

Use whereNotBetween().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

In QueryBuilder, how to return only rows where a column value can be found in a list of given values?

A

Use whereIn()…

$closeBy = DB::table(‘contacts’)

- >whereIn('state', ['FL', 'GA', 'AL'])
- >get();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

In QueryBuilder, how to select only rows where a given column is NULL or is NOT NULL?

A

Using whereNull(colName) or whereNotNull(colName)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What directory are the views stored in?

A

resources/views

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

In QueryBuilder, what function would you use to select only rows that when passed into a provided subquery, return at least one row.

A

whereExists()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Using QueryBuilder, get those users who have left at least one comment.

A
$commenters = DB::table(‘users’)
    ->whereExists(function ($query) {
        $query->select(‘id’)
            ->from(‘comments’)
            ->whereRaw(‘comments.user_id = users.id’);
    })
    ->get();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

The most common tool for accessing user data in Laravel is…

A

Injecting an instance of the Illuminate\Http\Request object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What are the alternatives to injecting an instance of the Request object?

A

There’s also a request() global helper and a Request facade. Each of these options exposes the entire Illuminate\Http\Request object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Write an example route that injects a Request object.

A
Route::post('form', function (Illuminate\Http\Request $request) {
    // $request->etc()
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

How would you obtain an instance of the current HTTP request via dependency injection?

A
Type-hint the Illuminate\Http\Request class on your controller method.
If your controller method is also expecting input from a route parameter you should list your route parameters AFTER the request like so:
public function update(Request $request, $id)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What method on the Request object gives you an array containing all of the input the user has provided, and then some?

A

$request->all()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

How to exclude fields from what the Request object show you?

A

$request->except()

Pass it either a string or an array of strings to exclude fields, otherwise provides the same output as $request->all()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What method is the inverse of $request->except()?

A

$request->only()

Pass it either a string or an array of strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What method is the inverse of $request->only()?

A

$request->except()

Pass it either a string or an array of strings.

47
Q

What method on the Request object can can detect whether a particular piece of user input is available?

A

$request->has()

You can also pass it an array of keys to check.

48
Q

What two methods on the Request object are for checking the presence of particular fields in the user input?

A

$request->has() determines if a value is present on the request. Pass it a string or array of strings.
$request->filled() determines if is present on the request AND is not empty. Pass it a string or array of strings.

49
Q

What method on the Request object gets the value of a single field?

A

$request->input()

Pass it the key you want and a fallback value. This fallback gets used ONLY if the key doesn’t exist, not if its null!

50
Q

What does the $request->method() method do?

A

Returns the HTTP verb for the request.

51
Q

What does the $request->isMethod() method do?

A

Checks whether the HTTP verb for the request matches the specified verb.

52
Q

Give a code example of using $request->isMethod()

A
if ($request->isMethod('patch')) {
// Do something if request method is PATCH
}
...the parameter is not case sensitive.
53
Q

How do you check what HTTP verb was used for a request?

A

$request->method() or $request->isMethod(‘verb’)

54
Q

What HTTP verb is associated with query strings?

A

GET

55
Q

What HTTP verb is associated with form submissions?

A

POST

56
Q

The HTTP verb GET is associated with what type of input?

A

Query strings

57
Q

The HTTP verb POST is associated with what type of input?

A

Form submissions

58
Q

What ‘housekeeping’ do you have to do whenever you’re using facades inside of namespaced classes (e.g., controllers)?

A

You’ll have to add the full facade path to the import block at the top of your file.
e.g.
use Illuminate\Support\Facades\Request;

59
Q

What is the full facade path to the Request facade?

A

Illuminate\Support\Facades\Request

60
Q

What are the two primary ways you’ll get data from the URL?

A

Via Request objects and via route parameters.

61
Q

Each group of characters after the domain in a URL is called a…

A

segment

62
Q

How many segments are in this URL? http://www.myapp.com/users/15/

A

Two, “users” and “15”

63
Q

What methods on the $request objects are available for returning URL segments?

A

$request->segments() returns an array of all segments,
$request-> segment($segmentId) gets the value of a single segment (1-based index)
These don’t return the query string.

64
Q

How to get data about the current URL from route parameters?

A

They are injected into the controller method or closure that is serving a current route.

65
Q

How would you get access to user uploaded files?

A

Using the Request object.
$request->file() takes the file’s input name as a parameter and returns an instance of
Illuminate\Http\UploadedFile

66
Q

Write the html markup of a simple form to upload files.

A

@csrf

67
Q

If you have in a form that get post’ed, what will $request->input(‘profile_picture’) return?

A

NULL, $request->input() doesn’t work on uploaded files.

68
Q

If you have in a form that get post’ed, what will $request->file(‘profile_picture’) return?

A

An instance of

Illuminate\Http\UploadedFile

69
Q

What method on the Request function would you use to check for the presence of a particular uploaded file?

A

$request->hasFile(‘profile_picture’)

Returns boolean

70
Q

How to check whether a file upload was successful?

A

$request->file(‘profile_picture’)->isValid();
or
$request->isValidFule(‘profile_picture’);

71
Q

What does the Illuminate\Http\UploadedFile class extend?

A

PHP’s SplFileInfo class

72
Q

Best practice for checking validity of an uploaded file?

A
Because isValid() is called on the file itself, it will error if the file didn’t upload. So you need to check for the file’s existence first:
if ($request->hasFile('profile_picture') && 
	$request->file('profile_picture')->isValid()) {
	//
}
73
Q

What common gotcha will lead to getting null when trying to get the contents of a file from $request?

A

Make sure you’ve set the encoding type on your form:

74
Q

What provides a convenient shortcut for the most common user-input validation workflow?

A

The $request->validate() method.

75
Q

Give some example code of the most basic use of request validation.

A

Route::post(‘recipes’, ‘RecipesController@store’);

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|unique:recipes|max:125',
        'body' => 'required'
    ]);
    // recipes is valid, go ahead and save it
}
76
Q

What if $request->validate() fails?

A

It throws a ValidationException. This returns a redirect to the previous page, together with all the input and validation errors.

77
Q

When will a ValidationException not return a redirect to the previous page?

A

If the request is from JavaScript or if it’s requesting JSON as a response. Then, the exception will create a JSON response containing the validation errors.

78
Q

The Illuminate\Http\Request extends which class?

A

Symfony\Component\HttpFoundation\Request

79
Q

What method returns the current request’s path?

A

$request->path()

80
Q

What method can verify that the incoming request path matches a given pattern?

A

$request->is(‘path’);
You can use wildcards like so:
if ($request->is(‘admin/*’)) { … }

81
Q

How to retrieve the full URL for the incoming request?

A

Either $request->url() or $request->fullUrl() (which includes the query string).

82
Q

What method does the same as $request->all()

A

$request->input() without any arguments

83
Q

While the $request->input() method retrieves values from entire request payload (including the query string), which method will only retrieve values from the query string?

A

$request->query() returns the query string as an associative array.
You can specify a key and fall-back value:
$request->query(‘name’, ‘Helen’);

84
Q

All of Laravel’s facades are defined in what namespace?

A

Illuminate\Support\Facades

85
Q

What are the three primary tools that Laravel provides for command-line interaction?

A

Artisan, Tinker and the installer.

86
Q

Artisan is actually a layer on top of…

A

The Symfony Console Component

87
Q

How to go about making a new Artisan command?

A

php artisan make:command CommandName –command=group:command
(PascalCase the command name).
The new command is located at app/Console/Commands/CommandName.php

88
Q

Where are custom Artisan commands stored?

A

Under app/Console/Commands/{CommandName}.php

89
Q

In writing an Artisan command, if you’d prefer not using facades, what to do?

A

Have Laravel’s container inject your dependencies by typehinting them in the command constructor:

class WelcomeNewUsers extends Command {
    public function \_\_construct(UserMailer $userMailer) {
        parent::\_\_construct();
        $this->userMailer = $userMailer
    } 
    public function handle() {
    	$this->userMailer->welcomeNewUsers();
    }
90
Q

How to add arguments to a custom Artisan command?

A

Define them in the $signature property of the command:

protected $signature = ‘password:reset {userID} {–sendEmail}’;

91
Q

What is the simplest way to define Artisan commands.

A
Closure-based commands can be defined in routes/console.php.
e.g.
Artisan::command(
    'password:reset {userID}',
    function($userID){
        $userID = $this->argument('userID');
        // do something...
})->descript('Reset a user password');
92
Q

What is Tinker?

A

A REPL (read-eval-print-loop) interactive shell for your application.

93
Q

How to exclude properties from an Eloquent model when outputting it as JSON?

A

Include the property names in the protected $hidden array.

94
Q

What is the easiest way to interact with the status of the authenticated user?

A

Use the auth() global helper. Or inject an instance of Illuminate\Auth\AuthManager or use the Auth facade.

95
Q

What does auth()->check() do?

A

Returns true if a user is logged in.

96
Q

What does auth()->guest() do?

A

Returns true if no user is logged in.

97
Q

What does auth()->user() do?

A

Returns the currently authenticated user. Returns null if no user is logged in.

98
Q

What does auth()->id() do?

A

Returns the currently authenticated user’s id. Returns null if no user is logged in.

99
Q

How to check whether any user is logged in?

A

auth()->check()

100
Q

How to check whether no user is logged in?

A

auth()->guest()

101
Q

How to get the currently authenticated user?

A

auth()->user()

102
Q

How to get the currently authenticated user’s id?

A

auth()->id()

103
Q

What is an alternative to auth()->user()?

A

Access the authenticated user via an Illuminate\Http\Request instance:
$request->user()

104
Q

How to define where users will be redirected to after user registration?

A

The $redirectTo property in the RegisterController.

105
Q

Where to edit the rules for validating and creating new user registrations?

A

In the RegisterController.

106
Q

How to customize the path the user will be redirected to after a successful login?

A

Edit the $redirectTo property in the LoginController.

107
Q

Where to place the code to perform any sort of behavior in response to a successful user login?

A

The AuthenticatesUsers trait calls the empty authenticated() method after a successful login, so just override this method in your LoginController.

108
Q

How to change which of the columns in your Users table is the username? What is the default?

A

Override the AuthenticatesUsers trait’s username() method in your LoginController to return the name of the column you want.
The default is ‘email.’

109
Q

How to add all the authorisation routes into your routes/web.php file?

A

Use the Auth::routes() convenience tool.

110
Q

How to enable Laravel’s email verification service for newly registering users?

A

In routes/web.php, update Auth::routes() to:

Auth::routes([‘verify’ => true]);

111
Q

How to check user authentication status in blade templates?

A

@auth
// user is authenticated
@endauth

@guest
// user is not authenticated
@endguest

112
Q

Every aspect of Laravel’s authentication system is routed through…

A

guards

113
Q

Explain the two pieces that for an authentication guard in Laravel.

A

the driver: defines how the guard persists and retrieves the authentication state (session).
the provider: allows you to get a user by certain criteria