Laravel Flashcards

Learn Laravel inside-out

1
Q

Write the simplest “Hello World” route.

A

Route::get(‘/’, function () {
return ‘Hello, World!’;
});

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

All of the configuration files for the Laravel framework are stored in…

A

The config directory.

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

How to override configuration values when running tests?

A

Create a .env.testing file. This overrides .env when running PHPUnit or executing Artisan commands with the –env=testing option.

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

How to retrieve environment variables from within config files?

A

Use the env helper.
‘debug’ => end(‘APP_DEBUG’, false);
Second argument is the default fallback.
Only call this within config files because once the configuration has been cached (php artisan config:cache) all calls to env() will return null.

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

How to determine the current environment? (dev/production etc)

A

Using the App facade, App::environment() returns the APP_ENV value from the .env file.

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

What does the App::environment method do?

A

Returns the APP_ENV value from the .env file. Pass it a string and it returns boolean if the env matches.
App::environment(‘local’); //true if in local
App::environment([‘local’, ‘dev’]); //true if in local OR dev

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

How to access configuration values (globally)?

A

Use the config helper function. Use dot-syntax of filename.option, eg:
$value = config(‘app.timezone’);

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

How to set configuration values at runtime?

A

Pass an array to the config helper:

config([app.timezone’ => ‘America/Chicago’]);

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

How to put an application into maintenance mode? and to disable maintenance mode?

A

php artisan down

php artisan up

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

What happens when a request is made and the application is in maintenance mode?

A

A MaintenanceModeException is thrown with status code 503 (service unavailable).

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

Where to customize the default maintenance mode template?

A

resources/views/errors/503.blade.php

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

How to generate a model in a ‘App/Models’ folder, and not in the default App folder?

A

php artisan make:model Models/Car

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

What does the bootstrap directory contain?

A

The app.php file which bootstraps the framework.

Also, a cache directory of cached files (eg routes and services)

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

What does the config directory contain?

A

All the applications configuration files.

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

What does the database directory contain?

A

Migrations, model factories, and seeds.

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

What does the public directory contain?

A

index.php - the entry point for all requests.

Also houses compiled assets such as JS and CSS.

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

What does the resources directory contain?

A

All views and un-compiled assets such as SASS and JS. Also language files.

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

What does the routes directory contain?

A

The route definitions: web, api, console and channels.

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

What does routes/web.php do?

A

Contains your web routes that the RouteServiceProvider places in the web middleware group, which provides session state, CSRF protection, and cookie encryption.

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

What does routes/api.php do?

A

Contains your API routes that the RouteServiceProvider places in the api middleware group, which provides rate limiting. These routes are stateless, so should be authenticated via tokens and will not have access to session.

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

What does routes/console.php do?

A

Contains your closure-based console commands.

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

What does routes/channels.php do?

A

Where you register all of the event broadcasting channels that your application supports.

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

What does the storage directory contain?

A

app directory to store application-generated files.
framework directory to store framework-generated files.
logs directory contains application’s log files.
storage/app/public to store user-generated files (is symbolically linked in public/storage)

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

What does the tests directory contain?

A

Feature and unit tests

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

What does the vendor directory contain?

A

Composer dependencies

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

What does the app directory contain? (And list default directories.)

A

The majority of your application. Namespaced under App and autoloaded by composer.
Directories: console, exceptions, http, providers

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

What is special about the app/console and app/http directories?

A

They can be thought of as providing an API into the core of your application. The HTTP protocol and CLI are two ways of issuing commands to your application, but do not actually contain application logic.

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

What does the app/console directory contain?

A

All your Artisan commands and the console kernel where commands are registered and scheduled.

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

What does the app/http directory contain?

A

Controllers, middleware and form requests.

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

What does the app/exceptions directory contain?

A

All your exception handlers. Also should be where you store custom exceptions. The default Handler class determines how exceptions are logged and rendered.

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

What does the app/providers directory contain?

A

All the service providers that bootstrap your application by binding services in the service container, registering events, or performing any other tasks to prepare your application for incoming requests.

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

What is the entry point for all requests to a Laravel app?

A

public/index.php

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

What are Facades?

A

They provide a ‘static’ interface to classes that are available in the application’s service container.

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

In what namespace are Laravel’s Facades defined?

A

Illuminate\Support\Facades

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

The most basic Laravel routes accept…

A

…a URI and a closure

36
Q

What is the default route file for your web interface?

A

routes/web.php

37
Q

What middleware are applied to routes/web.php?

A

The web middleware group is applied, which provides features like session state and CSRF protection.

38
Q

What middleware are applied to routes/api.php?

A

The api middleware group is applied. It is stateless (has no sessions).

39
Q

How to redirect a route to another URI?

A

Use Route::redirect(‘/here’, ‘/there’);
This provides a shortcut so you don’t have to define a controller for performing a simple redirect.
It returns 302 status by default (can customise this using the optional third parameter).

40
Q

How to return a permanent redirect on a route?

A

Route::permanentRedirect(‘/here’, ‘/there’); returns a 301 status code.

41
Q

If you don’t need a controller, how to return a view from a route?

A

Route::view(‘/welcome’, ‘welcome’);

Accepts a URI and a view name. You may pass data as an associative array in the third, optional, argument.

42
Q

In what order are route parameters injected into route callbacks/controllers?

A

Only based on their order. The names of the callback/controller arguments do not matter.

43
Q

What are route parameter naming constraints?

A

Only alphabetic, always encased in { } and may contain an underscore but NOT a hyphen.

44
Q

Write a simple route with a closure that takes two parameters.

A

Route::get(‘/posts/{post}/comments/{comment}’, function ($postId, $commentId) { … });

45
Q

Write a simple route with a close that takes an optional parameter.

A

Route::get(‘user/{name?}’, function ($name = null) { … });

Make sure to supply a default value.

46
Q

Why would we name routes? Write a simple route, named.

A

They allow convenient generation of URLs or redirects. Define by chaining the name method onto the route definition:
Route::get(‘user/profile’, ‘UsersController@show’)->name(‘profile’);

47
Q

How to generate a URL to a named route?

A

Using the route helper.

$url = route(‘profile’);

48
Q

How to generate a redirect to a named route?

A

return redirect()->route(‘profile’);

49
Q

If a named route defines parameters, how to pass them to the route helper function?

A

As an associative array in the second parameter:

$url = route(‘profile’, [‘id’ => 1]);

50
Q

If you pass more parameters to the route helper function that there are defined in the route, what happens?

A

They get added to the URL’s query string.

51
Q

How to determine whether the current request was routed to a given named route?

A

Use the named method on a Route instance:
$request->route()->named(‘profle’);
// returns boolean

52
Q

How does form method spoofing work?

A

Since HTML forms don’t support PUT, PATCH or DELETE, you need to add a hidden _method field with value set to the verb.
< form>
< input type=”hidden” name=”_method” value=”PUT”>
< input type=”hidden” name=”_token” value=”{{ csrf_token() }}”>
< /form>

Blade directive/shorthand:
< form>
  @method('DELETE')
  @csrf
< /form>
53
Q

Briefly describe middleware.

A

It provides convenient mechanisms for filtering incoming requests.

54
Q

Where are the middleware located?

A

app/Http/Middleware

55
Q

How do you create a new middleware?

A
php artisan make:middleware CheckSomething
Places a new class in app/Http/Middleware. Here our handle method can redirect if necessary or let them pass with return $next($request);
56
Q

How to register global middleware?

A

Middleware that is to be run on every request gets listed in the $middleware property in app/Http/Kernel.php

57
Q

Where is the VerifyCsrfToken middleware registered by default?

A

In the ‘web’ middleware group.

58
Q

Give a brief explanation of what controller do.

A

Controllers group related request handling logic into a single class, instead of defining all your request handling logic as Closures in route files.

59
Q

What is the syntax of a basic route to a controller action?

A

Route::get(‘user/{id}’, ‘UserController@show’);

60
Q

How to generate an invokable controller? Howto write the route?

A

A single-action controller is made by Artisan:
php artisan make:controller ShowProfile –invokable
Route::get(‘user/{id}’, ‘ShowProfile’); // no need for method name

61
Q

What does Route::resource do? Syntax?

A

Resource routing assigns CRUD routes to a controller in a single line of code.
Route::resource(‘photos’, ‘PhotoController’);

62
Q

How to generate a resource controller?

A

php artisan make:controller PhotoController –resource

63
Q

What is the syntax for registering many resource routes / resource controllers at once?

A

Route::resources([
‘photos’ => ‘PhotoController’,
‘posts’ => ‘PostController’,
]);

64
Q

What actions are handled by a resource controller and their respective routes and verbs?
Using example:
Route::resource(‘photos’, ‘PhotoController’)

A
VERB /URI (CONTROLLER METHOD)
get /photos (index)
get /photos/create (create)
post /photos (store)
get /photos/{photo} (show)
get /photos/{photo}/edit (edit)
put or patch /photos/{photo} (update)
delete /photos/{photo} (destroy)
65
Q

How are resource routes named?

A

Each is names as “base_URI (dot) controller_method” eg:
Route::resource(‘photos’, ‘PhotoController’) generates names like:
photos.index (for GET /photos)
photos.create (for GET /photos/create)
photos.store (for POST /photos)
etc.

66
Q

How to generate a model while making a resource controller?

A

php artisan make:controller PhotoController –resource –model=Photo

67
Q

Give a three line example of spoofing form methods with blade.

A

< form action”/foo/bar” method=”POST”>
@method(‘PUT’)
< /form>

68
Q

How to specify only a subset of actions on a resource route?

A
Either:
Route::resource('user', 'UserController')->only([
    'index', 'show'
]);
or
Route::resource('user', 'UserController')->except([
    'update', 'destroy'
]);
69
Q

What two actions are typically excluded from API resource routes?

A

Create and edit, because they are intended to present HTML form templates.

70
Q

How to automatically exclude the create and edit routes from a resource route? and for what purpose?

A

Route::apiResource(‘photos’, ‘PhotoController’);

There are excluded from API routes because they are typically expected to present user-fillable HTML forms.

71
Q

How to generate an API resource controller?

A

php artisan make:controller API/PhotoController –api

72
Q

How to obtain an instance of the current HTTP request in a controller method?

A

Dependency inject via type-hinting Illuminate\Http\Request on your controller method. Will be automatically injected by the service container.

73
Q

Whereto list route parameters if your controller method is already type-hinting other dependencies.

A

Always list route parameters AFTER other dependencies. eg:

public function update(Request $request, $id)

74
Q

How to retrieve the ‘request path’ and what is it?

A

$uri = $request->path();

If the full uri is http://domain.com/foo/bar then the request path is foo/bar

75
Q

How to check whether the incoming request path matches a given pattern?

A

if ($request->is(‘admin/*’)) { … }

76
Q

What is the difference between the request path and the URL?

A

If the URL is http://domain.com/foo/bar then the request path is foo/bar.

77
Q

How to retrieve the current request’s URL?

A

Without query string…
$url = $request->url()
With query string…
$url = $request->fullUrl();

78
Q

How to retrieve or check the request method (verb)?

A

$method = $request->method();

if ($request->isMethod(‘post’)) { … }

79
Q

What sort of responses can be returned? (name 6)

A

strings,
arrays (will automatically convert to JSON),
Eloquent collections (will automatically convert to JSON),
Full Illuminate\Http\Response instances,
redirects, or
views

80
Q

Returning a full Response instance allows you to…

A

… customize the response’s HTTP status code and headers.

81
Q

Where are views stored?

A

In resources/views

82
Q

How to access views within sub-directories? eg, write code to return the view resources/views/admin/profile.blade.php

A
with dot notation...
return view('admin.profile', $data);
83
Q

How to determine whether a view file exists?

A

With the View facade…

use Illuminate\Support\Facades\View;

if (View::exists('emails.customer')) {
    //
}
84
Q

What is the second argument passed to return view(‘page’, ?);

A

An array of data that should be made available to the view.

85
Q

What are two alternative ways of passing data to views using return view(‘abc’…?

A

Either as an associative array (kay / value pairs), or you may chain on ->with method to add individual pieces of data to the view.