Laravel Flashcards

1
Q

How do you create a laravel project?

A

laravel new dev.todoparrot.com

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

In the laravel project folder, what is the .env file for?

A

Managing settings to do with the project, such as database passwords etc.

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

What does the .gitattributes file do?

A

Used to maintain consistent settings across machines

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

What does .gitignore do?

A

Tells git which files to ignore from the repository

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

What is in the app directory?

A

Most of the custom code written for the project

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

What is the artisan command in the root directory?

A

A command line configuration tool

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

What is the bootstrap directory?

A

All the code required to initialise and start up the laravel application

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

What is in the config directory?

A

Mainly basic configuration files and things like database credentials, cache and email settings

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

What is gulpfile.js?

A

Used as part of elixir, it is used to automate compilation of css and js files.

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

What is package.json?

A

Used by elixir to install elixir and it’s various dependencies.

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

What is phpspec.yml?

A

Used to configure the behavior driven tool PHPSpec (I believe testing)

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

What is phpunit.xml?

A

PHPUnits configuration file for laravel.

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

What is the public directory?

A

The root directory of the application.

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

What is the other term for the index.php file in the public folder?

A

The frontcontroller.

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

What is in the resources folder?

A

Projects views and localised language files. You can also store your raw resources here such as coffee script etc.

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

What is the vendor folder for?

A

That is where the laravel and other related code is stored (via composer).

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

How do you start the built in laravel server?

A

php artisan serve

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

How do you set the namespace for your new laravel app?

A

php artisan app:name myprojectname

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

When setting a new namespace using the artisan command, what is updated?

A

All controllers / models any other relevant files as well as the composer.json file (psr-4 settings for autoloading)

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

The app.php file is in the config directory, what does it contain?

A

App wide settings including things like debug information.

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

The auth.php file is in the config directory, what does it contain?

A

Settings specific to authentication, including which model manages users, how password reminders are managed, database tables containing user information.

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

The broadcasting.php file is in the config directory, what does it contain?

A

Contains information pertaining to the way laravels new broadcast feature operates.

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

The cache.php file is in the config directory, what does it contain?

A

Contains configuration information for different caching modules.

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

The compile.php file is in the config directory, what does it contain?

A

Laravel can improve performance by generating a series of files that allow for faster package loading - this file allows you define which classes should be added and included in the final optimisation step.

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

The database.php file is in the config directory, what does it contain?

A

Database authorisation credentials as well as the database module it will support.

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

The filesystems.php file is in the config directory, what does it contain?

A

The configuration file defines the different file systems the project will handle for file uploads. Could be localdisk, amazon s3 or rackspace.

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

The mail.php file is in the config directory, what does it contain?

A

Various settings for sending mail in php.

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

The queue.php file is in the config directory, what does it contain?

A

Queues can improve performance by offloading certain tasks to queueing solutions such as beanstalk and Amazon Simple Queue Service.

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

The services.php file is in the config directory, what does it contain?

A

If your application uses any third party services such as stripe, this file will allow configuration of those files.

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

The session.php file is in the config directory, what does it contain?

A

You can use a number of different session management services such as filesystem, cookies, database - configure the options here…

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

The view.php file is in the config directory, what does it contain?

A

Configure the location for the templates for the views and renderer used for pagination.

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

Laravel refers to the development environment as what?

A

local environment

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

Settings in the .env file can be retrieved by using which function?

A

env()

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

What builtin function can be used to print debug information about arrays / objects etc?

A

dd()

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

Where is the default location for laravel to store logs?

A

storage/logs/laravel.log

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

What 3rd party app manages laravels logging?

A

monolog

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

How would you write to the log in laravel?

A

\Log::debug($item);

$item could be a string, or array what ever.

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

How do you specify the logging severity?

A

\Log::warning($item);
\Log::info($item);
\Log::error($item);
\Log::critical($item);

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

How can you get debug information to appear in a firefox window/

A

You need to install firebug, and FirePHP extension

You trigger it through monolog->pushHandler

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

How do you perform interactive debugging in Laravel?

A

Use tinker

php artisan tinker –env=local

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

Once you’ve added a new package (such as debugbar) to the vendors directory via composer, how do you install it?

A

You need to add an entry in the config/app.php for both the aliases and providers array.

Then you must run the following command:

php artisan vendor:publish

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

How do you render a message to the debug bar?

A

\Debugbar::error(‘Something is definitely going wrong’);

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

How can you make a composer package globally available?

A

Use the command

composer global

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

There is an issue with Laravel 5.1 and the “laravel new” command, what is it?

A

It doesn’t simlink the phpspec or phpunit files - causing an error message.

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

If you place a view in a subfolder of the view directory, how do you reference this in code?

A
Use dot notation.
return view('home.welcome');
This will access a file called welcome.blade.php in the home directory which is in the base view directory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

How do you make a new controller in laravel?

A

php artisan make:controller –plain NameOfController

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

What happens if you ommit the –plain flag when using artisan to create a controller?

A

Laravel will create a controller containing stubs for a RESTful controller.

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

If you use “php artisan make:controller” to make a new controller, where is it created?

A

app/Http/Controllers/NameOfController.php

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

In the laravel community, a RESTful controller is often referred to as…

A

Resource Controller

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

It is common to associate one controller with one what?

A

Resource - i.e. ListsController will only get a ‘list’ or set of ‘lists’.

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

How would you get a list of all available routes?

A

php artisan route:list

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

How do you cache your routes?

A

php artisan route:cache

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

If you add, edit or delete a route after caching your routes, what must you do?

A

either clear or rebuild the routes

route: clear
route: cache

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

What must be present in a view filename so that laravel recognises it as a blade augmented file?

A

.blade.php

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

Passing multiple variables into the view function can be messy, how can we simplify this?

A
Use the PHP function compact:
$name = "foobar";
$date = date('Y-m-d');
return view('home.welcome', compact('name', 'date'));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How could you use a default value in a blade, if the wanted variable was not set?

A

welcome {{ $name or ‘superman’ }}

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

In laravel 5 there was a change to the way output is escaped in a blade template, how is it done now (used to be {{{ }}} - triple braces)?

A

{!! ‘my list alert(‘go fuck yourself’)’ !!}

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

What is the loop syntax in a blade template?

A

@foreach ($lists as $list)
{{ $list }}
@endforeach

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

What can you do to mitigate risk of an array being empty in a blade template?

A

Use a forelse loop

@forelse ($lists as $list)
    {{ $list }}
@empty
    "You don't have anything in that list!"
@endforelse
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

How can we test if an array is full / empty?

A
@if(count($lists) > 0) 
   // Do something
@else
   // Do something else
@endif
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is the else-elseif-else syntax?

A
@if (count($lists) > 0)
   // Do stuff
@elseif (count($lists) == 1)
  // Do otherstuff
@else 
  // Do yet more stuff if the otherstuff didn't pan out
@endif
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What is the ‘blade’ methodology for dealing with templates (such as header/footer etc)?

A

Using what is called a “master layout”.

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

What blade function to we use to tell the blade system what to place in a section of the template?

A

@yield(‘content’)

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

When building a blade that should use a master layout, how do you tell the system which layout to use

A

@extends(‘layout.master’)

Assuming there is a folder called layout with a blade called master in it

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

In the layout - we use the function ‘yield’, and pass it the name of the section that should go here. How do identify this section in the blade file that is using the master layout?

A

@section(‘content’)
// Put stuff in here.
@endsection

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

What is the purpose of the @section / @show combination (in the master layout)?

@section(‘title’);
Laravel
@show

A

This can be used to append content from a page, using the @parent call

@section(‘title’)
@parent
:: some page
@stop

Would give you in the output

Laravel :: some page

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

How could you have default content in a blade?

A

One of two ways - use the @section @show combination. It sets up a section, and yields it straight away.

Or use @section(‘section’, ‘default value’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q
If you wanted to remove the parent templates html in a particular section, how would you change the following code?
@section('title')
@parent
   :: some page
@stop
A

Simply remove the @parent directive

@section(‘title’)
:: some page
@stop

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

How would you make the following code prepend the template data, rather than append?

@section(‘title’)
@parent
:: some page
@stop

A

Change the location of the @parent call

@section(‘title’)
:: some page
@parent
@stop

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

What is the laravel name for the concept of managing smaller components (i.e. widgets) for a webpage, but in it’s own template?

A

view partials

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

Images, CSS and JS should be placed where?

A

The public directory of the app (root folder contains the public folder)

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

How do you reference HTML and JS files?

A

You can use standard HTML, or you can use the facade. However, you have to include the facade as it’s not a standard part of Laravel anymore. “LaravelCollective/HTML”

Syntax

{!! HTML::image(‘images/logo.png’, ‘todoparrot logo’); !!}

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

What are the two best ways to test customer interaction of a web page? (I.e. if I click on this link, do I get the expected page?)

A

You can use one of two packages - the built in (as of laravel 5.1) HTTP request API, or you can use a third party composer package called Goutte, which contains a web crawler that can determine if links exist.

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

What does the ‘fetch’ field mean in the laravel config/databases file?

A

It specifies how Eloquent will retrieve SQL data. By default it retrieves data in PHP stdClass format.

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

How do you create a model?

A

php artisan make:model Todolist

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

How do you crate a migration?

A

When using make:model - you can supply the -m switch.

php artisan make:model Todolist -m

Otherwise:

php artisan make:migration create_todolist_table

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

If a model is named Todolist, what is the underlying database named?

A

todolists

The models are singular and the tables underneath are plural.

78
Q

What is the second parameter in the env() method used for?

A

It is used as a default value, if the first parameter cannot be found in the projects associated .env file.

env(‘DB_NAME’, ‘localhost’);

79
Q

A laravel model is a class that extends which laravel class?

A

Model

80
Q

A migration file is just a class, but what class does it extend?

A

Migration

81
Q

What do the methods, up() and down() do on a migration class?

A

They define what happens when a migration is expected and reverted.

82
Q

What class is often used in laravel to manipulate database tables?

A

Schema

83
Q

What Schema method deletes a table?

A

Schema::drop()

84
Q

What Schema method creates a table?

A

Schema::create()

85
Q

What does the following code do in a Migration?

$table->increment(‘id’);

A

Creates an automatically incrementing id named id, that will serve as the tables primary id.

86
Q

$table->timestamps()

A

The timestamps() method informs laravel to include created_at and updated_at timestamp columns, which are automatically updated.

87
Q

In a Schema::create closure, how would we indicate we wanted to create a column called name of type Varchar?

A

$table->string(‘name’);

88
Q

In a Schema:create closure, how would we indicate that we wanted to create a column called description that is of type TEXT?

A

$table->text(‘description’);

89
Q

How do we trigger a migration (to create a new table)?

A

php artisan migrate

90
Q

If you execute the command to create a migration (databse table) and it’s the first time running it, what else is created?

A

The migration table which contains information used for rolling back / forward stuff.

91
Q

If you create three migrations and run them all under one command, what happens when you want to roll back one of them?

A

These are all treated as part of the same batch, and so rolling back one will require rolling back all of them.

92
Q

What command do you run to rollback a migration?

A

php artisan migrate:rollback

93
Q

How do you add a column to a table via migrations?

A

php artisan make:migration create_todolist_table –table=todolist

NOTE: We have to specify the table name when we are deleting or adding a column.

94
Q

How do we use the artisan make command to create a migration?

(It seems that Laravel doesn’t create a migration automatically with make:model was described in the book)

A

php artisan make:migration create_todolist_table

95
Q

In the migration file - how would you specify a new column to be added at a certain location within the database?

A

Use the after method.

$table->string(‘foobar’, 100)->after(‘id’);

100 is the length.

96
Q

How do you determine the status of current migrations?

A

php artisan migrate:status

97
Q

Laravel models are POPO’s. What’s a POPO?

A

Plain old PHP object.

98
Q

What is the convention for creating a getter on a model?

A

getAttributeName

NOTE: This is not accessed via a method - laravel will search for the Accessor using magic methods. You call it like this:

$username = $user->username

Laravel will call: User::getUsername

99
Q

What is the difference between an Accessor and a Virtual Accessor?

A

Virtual Accessors retrieve data, usually combined data. So for instance, rather than getting first name and last name, it combines them into a single name.

Accessors tend to only return the exact attribute - and the only real thing you can do with them is for example, making a first name all lowercase. This is probably not the concern of the model as that should be in the presentation layer. However, with a Virtual Accessor, you are implementing business rules, which belongs in the model.

100
Q

If you are using PsySH (via tinker) - what do you have to do before playing with amodel?

A

You must declare the namespace

> > > namespace Todoparrot;
=> null
$list = User::find(1);
echo $list->fullname;

101
Q

When do you use a mutator?

A

When you want to modify the value of an attribute. NOTE: These are also known as ‘setters’

102
Q

Laravel recognises mutators when they are set with which convention?

A

setAttributeNameAttribute

i.e. for an attribute with the AttributeName of password

setPasswordAttribute($password) - But you call it like this:

$user->password = ‘blah’;

103
Q

How do you stay… DRY?

A

Don’t Repeat Yourself

i.e. use lots of custom methods to keep extra code out of controllers

104
Q

Is model based data validation (laravel style) used in all cases?

A

No - it’s not necessary for form validation - you can use a form requests feature from Laravel 5 for that.

105
Q

How do you setup rule validation within a model?

A

You create an array called rules - where the rules are configured.

private $rules = [
‘name’ => ‘required’,
‘email’ => ‘required | email | unique:users’
];

106
Q

How do we setup the validation logic for a model?

A

Within a class - create a ‘validate’ method, and use the Laravel Validator class.

public function validate()
{
    $v = \Validator::make($this->attributes, $this->rules);
    if ($v->passes()) return true;
    $this->errors = $v->messages();
    return false;
}
107
Q

When using mass-assignment into a model (i.e. via an array of data) - what must you do to ensure Laravel is happy with you commiting the data to the database?

A

You must define the protected ‘$fillable’ property of the model. It is an array of attribute names from the model.

108
Q

If you have MANY elements in a model, it would be annoying to have specify all of them in the $fillable property, what is the other option if you just want to prevent a couple of the attributes from being written to in a mass way?

A

You can use the ‘guarded’ attribute.

protected $guarded = [‘name’, ‘description’];

Works the reverse of $fillable.

109
Q

Laravel creates RESTful controllers by default - but it doesn’t know that you intend to use them in a RESTful manner. How do you instruct it to do so?

A

You need to setup a route in the routes.php file

Route::resource(‘lists’, ‘ListsController’);

110
Q

Where is the routes file in Laravel 5?

A

app/Http/routes.php

111
Q

What is the difference between setting up a straight forward route for a GET request and a RESTful route?

A

a GET request (i.e. a standard route) is:
Route::get(‘/’, ‘WelcomeController@index’);
a RESTful route refers to the resource
Route::resource(‘list’, ‘ListsController’);

112
Q

How can you use the model to get the total count of all elements in the table?

A

echo Todolist::all()->count();

113
Q

Laravel’s blade templating engine exposes the PHP objects as what?

A

Simple PHP objects - you can just use normal PHP notation to get access to the variables / values.

114
Q

What command is used to seed the database?

A

php artisan db:seed

115
Q

What file does the db:seed command execute?

A

database/seeds/DatabaseSeeder.php

116
Q

Where are the seed files located?

A

database/seeds

117
Q

When you’ve created a database seed file, what is the one step you’ll have to do before running the seeder?

A
Rebuild the class map
composer dump-autoload
118
Q

How do you rebuild the class map using composer?

A

composer dump-autoload

119
Q

How would you use the DB class to remove a table?

A

DB::table(‘foobar’)->delete();

120
Q

What library (included with 5.1 by default) can be used to generate large amounts of test data?

A

Faker

121
Q

What does the command

Todolist::truncate()

do?

A

Deletes all of the records in the Todolist model.

122
Q

If we see a variable like such:

$lists = Todolist::all()

we know it is of type….

A

Illuminate\Database\Eloquent\Collection

123
Q

The Collection class is…

A

iterable

124
Q

What is one way we can access the data within an iterable class?

A
foreach($lists as $list) {
   // Do stuff
}
125
Q

Rather than using PHP’s foreach method to iterate through an Eloquent collection, what is the other option?

A

$lists = todoparrot\Todolist::all();
$lists->each(function($list){
echo $list->name;
});

This is the Eloquent method of iteration.

126
Q

Rather than using a collections “all” method to obtain all of the data, how would you retrieve an individual record using the ID?

A

$list = Todolist::find(3);

127
Q

Where do error views live?

A

resources/views/errors

128
Q

Where do we put our custom exception handlers?

A

app/Exceptions/Handler.php

129
Q

If you get the following error, what should you potentially check for?

No query results for model [todoparrot\Todolist].

A

It could be that you are referencing a class that is not in scope - make sure you have the ‘use foobar\bar’ clause at the beginning of the file.

130
Q

For performance reasons it’s best not to retrieve all fields on a table - how do you restrict this in code?

A

Use select

Todolist::select(‘name’, ‘description’)->first()

131
Q

How can you get a count of the records selected in a Eloquent collection from within the blade?

A

{{ $lists->count() }}

132
Q

How can you order records?

A

$lists = Todolist::orderby(‘name’)->get();

133
Q

When do you use the ->get() method?

A

It’s typically used when all() or find() is not being used. Setup a query, and call that on the end to retrieve the result.

134
Q

What is the Laravel default sort order?

A

Ascending

135
Q

How do you change the sort order of a query?

A

When using the orderby method, you can pass ASC or DESC as the second parameter to the method.

$lists = Todolist::orderby(‘name’, ‘DESC’)->get()

136
Q

How would you order results when multiple columns are involved?

A

You can specify the order on each column

$lists = Todolist:orderby(‘created_at’, ‘DESC’)

         - >orderby('name', 'ASC')
         - >get();
137
Q

How could you select all of the lists in a class called Todolist, that had the field ‘completed’ set to true?

A

$lists = Todolist::where(‘completed’, ‘=’, 1)->get();

138
Q

What is the Laravel safeguard against SQL injection when using the ‘where’ method?

A

The method requires the variable we are testing, the test operator, and the value to be tested against to be sent separately to the method. This prevents straight up user input being passed to the query.

139
Q

What is the whereRaw interface for?

A

Should you not be able to generate the query via the fluent interface, then you can use whereRaw - which kinda works like PDO prepared statements.

$users = User::whereRaw(‘age > ? and votes = 100’, array(25))->get();

140
Q

How would you create the following SQL query in Eloquent?

SELECT year(created_at) as year, count(name) as count FROM todolists GROUP BY year ORDER BY count DESC

A

$lists = Todolist::select(DB::raw(‘year(created_at) as year’), DB::raw(‘count(name) as count’))

  • > groupBy(‘year’)
  • > orderBy(‘count desc’)->get();
141
Q

What is DB:raw?

A

Laravels query builder - but it’s excellent for passing SQL aggregate functions into the query, as Eloquent does not support aggregate functions as yet.

142
Q

In MySQL, the WHERE clause is applied before the aggregate functions, meaning you can’t use WHERE to filter against aggregate values - what Eloquent function would you use to achieve this?

A

->having(‘year’, ‘>’, ‘2010’)->get()

Much like MySQL - you would use the having function for this kind of query

143
Q

This MySQL function will get 5 records starting from the 6th record. How would you achieve this with ELOQUENT?

SELECT * FROM todolists ORDER BY created_at LIMIT 5 OFFSET 5

A

$lists = Todolists::take(5)->skip(5)->orderBy(‘created_at’, ‘desc’)->get();

144
Q

How would you retrieve the first item in a model?

A

$list = Todolist::orderBy(‘created_by’, ‘desc’)->first()

145
Q

You use the first() method to get the first element in a list - how do you get the last?

A

You also use ‘first()’ - but you reverse the sort order to get the last item:

$list = Todolist::orderBy(‘created_by’, ‘asc’)->first()

146
Q

This command retrieves one random list from a database - why is it so inefficient, and what should you do instead?

$list = Todolist::all()->random(1);

A

It is inefficient, because it has to first retrieve ALL records from the database. The better option is to use a DB::raw call to do the random bit.

$list = Todolist::orderby(DB::raw(‘RAND()’))->first()

147
Q

Why is the following method efficient?

$exists = Todolist::where(‘name’, ‘=’, ‘San Juan’)->exists();

A

Because it doesn’t retrieve the record in order to determine whether it exists.

148
Q

How do you use pagination?

A

$list = Todolist::orderby(‘created_at’)->pagination(10);

149
Q

Once you have called the pagination() method - you will receive any objects that match the query, but how do let the user choose the next page?

A

You need to embed the pagination navigation - in a blade you use:

{!! $lists->render() !!}

150
Q

How would you create a new record using the ‘save’ method?

A

$list = new Todolist;
$list->name = ‘sam’;
$list->description = ‘large boobs, nice vag’;
$list->save();

(NOTE: Id will be created if it is an autoincrement field already in the database)

151
Q

What is the alternative to the ‘save’ method when creating a new database object?

A

The create method - it creates and saves in one call.

$list = Todolist::create(
array(‘name’ => ‘San Juan Vacation’,
‘description’ => ‘Fun times’
);

152
Q

How would you retrieve a model instance or create a new one if it doesn’t exist?

A

$list = Todolist::firstOrNew(array(‘name’=>’billy bob’));
$list->description(‘Yo - this is fun!’);
$list->save();

You can also use firstOrCreate - but it has some odd behavior…

153
Q

How would you update a model instance or create a new one if it doesn’t exist?

A

$list = Todolist::updateOrCreate(
array(‘name’ => ‘San Juan Vacation’),
array(‘description’ => ‘Soooo much fun’)
);

First attribute is used to search for an existing record, the second attribute is used to specify what to insert / update if one is found.

If there is no existing record then the values in both parameters will be inserted into the new record.

154
Q

How do you delete a record?

A

$list = Todolist::find(12);
$list->delete();

or

$list->destroy(12);

which consolidates the above commands.

155
Q

How do you redirect to a named route?

A

return \Redirect::route(‘login’);

156
Q

What is a soft delete?

A

Rather than removing the data from the database, you just flag the entry so that it remains, but is treated as deleted.

Laravel natively supports soft deletion.

157
Q

How do you setup soft deletes in Laravel?

A

In the migrate file:

Schema::table(‘todolists’, function(Blueprint $table) {
$table->softDeletes();
});

158
Q

What has to happen in the model to enable soft deleteing?

A

Include the softDeletes trait.

use Illumate\Database\Eloquent\SoftDeletes;
class TodoList extends Model {
   use SoftDeletes;
   protected $data = ['deleted_at'];
}
159
Q

By providing a date attribute in the following format, it forces Laravel to store the dates as type…

protected $data = [‘deleted_at’];

A

Carbon

160
Q

If a record has been soft deleted, how do you go about finding it?

A

$list = Todolist::withTrashed()->get();

161
Q

How do we get all of the records through the Laravel builder interface?

A

$lists = DB::table(‘todolists’)->get();

Returns a group of objects of type stdClass

162
Q

How do you find a specific record when using the Laravel builder class?

A

$list = DB::table(‘todolists’)->find(52);

163
Q

How would you get just the name column of a table?

A

$lists = DB::table(‘todolists’)->select(‘name’)->get();

164
Q

How would you use the Laravel builder class to execute raw SQL?

A

$lists = DB::select(‘SELECT * FROM todolists’);

165
Q

What laravel builder method would you use to delete an element with raw SQL?

A

DB::delete(‘delete from todolists where completed = 1’);

166
Q

What laravel builder method would you use to update an element with raw SQL?

A

DB::update(‘update todolists set completed = 1 where id = ?’, array(52));

167
Q

What laravel builder method would you use to insert an element with raw SQL?

A

DB::insert(‘insert into todolists (name, description) values (?, ?)’, array(‘superman’, ‘cocksniff’));

168
Q

If you want to run an administrative command, or a command that doesn’t interact directly with the actual database - what would you use?

A

$lists = DB::statement(‘drop table todolists’);

169
Q

What package can be used to create sluggable models?

A

Cviebrock/eloquent-sluggable

170
Q

If you are using PHPUnit for testing - how do you override the Laravel database settings so that you can use a specific test database?

A

You can add database configuration information to the phpunit.xml file.

NOTE: The DB_USERNAME and other .env variables will be used as usual - but here we override the database name specifically so we can point the PHPUnit testing environment at a different database.

171
Q

What is the best way to make sure the PHPUnit tests you are doing are consistent and maintain integrity?

A

Tear down and rebuild the database before each set of tests so you are working with known data.

172
Q

How do you make your PHPUnit tests dump / rebuild the databases before running tests?

A

Add the trait DatabaseMigrations.

use DatabaseMigrations;

173
Q

How do you setup a model factory so that it can be used to generate data in the test suites?

A

In the folder ‘database/factories/’ there is a file called ModelFactory.php. You can add this code:

$factory->define(App\Todolist::class, function ($faker) {
    return [
        'name' => 'blah',
        'description' => $faker->name
    ];
});

Which can later be called in a test like this:

$listFactory = factory(‘App\Todolist’)->create();

174
Q

What is the difference between the following commands?

factory(‘App\Todolist’)->create();
factory(‘App\Todolist’)->make();

A

create() actually creates data in the database. Make() will simply create the Todolist object which is local to the test.

175
Q

If you do not need to retrieve data from the database over the course of the test - which version of the factory method should you use, create or make?

A

make() - it doesn’t hit the database and thus is faster.

176
Q

How would you write a PHPUnit test to test whether a particular class could be instantiated correctly?

A

$list = new Todolist;

$this->assertEquals(get_class($list), ‘todoparrot\Todolist’);

177
Q

When specifying an integer column as a foreign key, what must you remember to do?

A

You MUST declare it as unsigned or else the migration will fail.

178
Q

How do you formalise a one-to-one relationship with two classes in laravel?

A

Typically you create a public method of the same name as the model the class has a relationship with. So if Profile has a foreign key that points to User - then Users should have a public method called ‘profile’. This method should return the value of the ‘hasOne’ method.

$this->hasOne(‘todoparrot\Profile’);

179
Q

How would you access a user’s telephone number (which exists in their profile) using the one-to-one relationship?

A

$user = User::find(212)->profile->telephone

180
Q

How do you create a one to one relationship?

A

You can create the child object and then save it through the parent object:

$profile = new Profile;
$profile->telephone = ‘544-45345-344’;
$user = User:find(212);
$user->profile()->save($profile);

181
Q

What happens if you delete a user that has an associated profile?

A

You can’t have a profile on it’s own, so it must be deleted.

$user = User::find(212);
$user->profile()->delete();

182
Q

In a database you can make a delete cascade, how would you simulate something like this in Eloquent to makes sure you avoid orphan tables?

A

When creating the migration - make sure you use the onDelete(‘cascade’) option:

$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);

183
Q

The hasOne relationship is a … way definition?

A

one way - i.e. you can get a profile from a user, but you can’t get a user from a profile.

184
Q

How do you create a two way relationship between two models?

A

model a must have a function that references model b - and will call hasOne.

Model b must have a function that references model a - and will call belongsTo

185
Q

If table B has a foreign key that links to table A - what kind of relationship does this imply?

A

A “belongs to” relationship - i.e. Table B belongs to Table A.

186
Q

What does it ensure if we use the references method in the following code when setting up a model?

$table->foreign(‘todolist_id’)
->references(‘id’)->on(‘todolists’);

A

Because this table expects to reference the other table (“todolists”) - Laravel will make sure the “todolist_id” field on this table is indexed.

187
Q

How would you filter a todolist (with id 1) that has a many to many relationship with a task list - to find tasks that are ‘done’?

A

$completedTasks = Todolist::find(1)->tasks()->where(‘done’, true)->get();

188
Q

What is the intermediary table called that links two tables in a many to many relationship?

A

A pivot table

189
Q

What does Laravel assume about pivot table naming?

A

That it is named by concatenating the two related tables together with an underscore.

190
Q

If we have Todolist and Category with a many to many relationship - how will the pivot table be named?

A

category_todolist

The name is in alphabetical order, and laravel assumes underscores.

191
Q

What does the “withTimestamps()” method do here?

return $this->belongsToMany(‘todoparrot\Category’)->withTimestamps();

A

It updates the “updated_at / created_at” fields on a table (as long as they exist). This is particularly used with pivot tables.

192
Q

How do you associate records in a many to many situation?

A

Same way as with a one to many method - laravel takes care of the behind the scenes stuff.

$tl = Todolist::find(1);
$category = new Category(array('name' => 'Vacation'));
$tl->categories()->save($category);