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
The database.php file is in the config directory, what does it contain?
Database authorisation credentials as well as the database module it will support.
26
The filesystems.php file is in the config directory, what does it contain?
The configuration file defines the different file systems the project will handle for file uploads. Could be localdisk, amazon s3 or rackspace.
27
The mail.php file is in the config directory, what does it contain?
Various settings for sending mail in php.
28
The queue.php file is in the config directory, what does it contain?
Queues can improve performance by offloading certain tasks to queueing solutions such as beanstalk and Amazon Simple Queue Service.
29
The services.php file is in the config directory, what does it contain?
If your application uses any third party services such as stripe, this file will allow configuration of those files.
30
The session.php file is in the config directory, what does it contain?
You can use a number of different session management services such as filesystem, cookies, database - configure the options here...
31
The view.php file is in the config directory, what does it contain?
Configure the location for the templates for the views and renderer used for pagination.
32
Laravel refers to the development environment as what?
local environment
33
Settings in the .env file can be retrieved by using which function?
env()
34
What builtin function can be used to print debug information about arrays / objects etc?
dd()
35
Where is the default location for laravel to store logs?
storage/logs/laravel.log
36
What 3rd party app manages laravels logging?
monolog
37
How would you write to the log in laravel?
\Log::debug($item); $item could be a string, or array what ever.
38
How do you specify the logging severity?
\Log::warning($item); \Log::info($item); \Log::error($item); \Log::critical($item);
39
How can you get debug information to appear in a firefox window/
You need to install firebug, and FirePHP extension You trigger it through monolog->pushHandler
40
How do you perform interactive debugging in Laravel?
Use tinker | php artisan tinker --env=local
41
Once you've added a new package (such as debugbar) to the vendors directory via composer, how do you install it?
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
42
How do you render a message to the debug bar?
\Debugbar::error('Something is definitely going wrong');
43
How can you make a composer package globally available?
Use the command composer global
44
There is an issue with Laravel 5.1 and the "laravel new" command, what is it?
It doesn't simlink the phpspec or phpunit files - causing an error message.
45
If you place a view in a subfolder of the view directory, how do you reference this in code?
``` 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. ```
46
How do you make a new controller in laravel?
php artisan make:controller --plain NameOfController
47
What happens if you ommit the --plain flag when using artisan to create a controller?
Laravel will create a controller containing stubs for a RESTful controller.
48
If you use "php artisan make:controller" to make a new controller, where is it created?
app/Http/Controllers/NameOfController.php
49
In the laravel community, a RESTful controller is often referred to as...
Resource Controller
50
It is common to associate one controller with one what?
Resource - i.e. ListsController will only get a 'list' or set of 'lists'.
51
How would you get a list of all available routes?
php artisan route:list
52
How do you cache your routes?
php artisan route:cache
53
If you add, edit or delete a route after caching your routes, what must you do?
either clear or rebuild the routes route: clear route: cache
54
What must be present in a view filename so that laravel recognises it as a blade augmented file?
.blade.php
55
Passing multiple variables into the view function can be messy, how can we simplify this?
``` Use the PHP function compact: $name = "foobar"; $date = date('Y-m-d'); return view('home.welcome', compact('name', 'date')); ```
56
How could you use a default value in a blade, if the wanted variable was not set?
welcome {{ $name or 'superman' }}
57
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)?
{!! 'my list alert('go fuck yourself')' !!}
58
What is the loop syntax in a blade template?
@foreach ($lists as $list) {{ $list }} @endforeach
59
What can you do to mitigate risk of an array being empty in a blade template?
Use a forelse loop ``` @forelse ($lists as $list) {{ $list }} @empty "You don't have anything in that list!" @endforelse ```
60
How can we test if an array is full / empty?
``` @if(count($lists) > 0) // Do something @else // Do something else @endif ```
61
What is the else-elseif-else syntax?
``` @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 ```
62
What is the 'blade' methodology for dealing with templates (such as header/footer etc)?
Using what is called a "master layout".
63
What blade function to we use to tell the blade system what to place in a section of the template?
@yield('content')
64
When building a blade that should use a master layout, how do you tell the system which layout to use
@extends('layout.master') | Assuming there is a folder called layout with a blade called master in it
65
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?
@section('content') // Put stuff in here. @endsection
66
What is the purpose of the @section / @show combination (in the master layout)? @section('title'); Laravel @show
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
67
How could you have default content in a blade?
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')
68
``` 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 ```
Simply remove the @parent directive @section('title') :: some page @stop
69
How would you make the following code prepend the template data, rather than append? @section('title') @parent :: some page @stop
Change the location of the @parent call @section('title') :: some page @parent @stop
70
What is the laravel name for the concept of managing smaller components (i.e. widgets) for a webpage, but in it's own template?
view partials
71
Images, CSS and JS should be placed where?
The public directory of the app (root folder contains the public folder)
72
How do you reference HTML and JS files?
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'); !!}
73
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?)
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.
74
What does the 'fetch' field mean in the laravel config/databases file?
It specifies how Eloquent will retrieve SQL data. By default it retrieves data in PHP stdClass format.
75
How do you create a model?
php artisan make:model Todolist
76
How do you crate a migration?
When using make:model - you can supply the -m switch. php artisan make:model Todolist -m Otherwise: php artisan make:migration create_todolist_table
77
If a model is named Todolist, what is the underlying database named?
todolists The models are singular and the tables underneath are plural.
78
What is the second parameter in the env() method used for?
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
A laravel model is a class that extends which laravel class?
Model
80
A migration file is just a class, but what class does it extend?
Migration
81
What do the methods, up() and down() do on a migration class?
They define what happens when a migration is expected and reverted.
82
What class is often used in laravel to manipulate database tables?
Schema
83
What Schema method deletes a table?
Schema::drop()
84
What Schema method creates a table?
Schema::create()
85
What does the following code do in a Migration? $table->increment('id');
Creates an automatically incrementing id named id, that will serve as the tables primary id.
86
$table->timestamps()
The timestamps() method informs laravel to include created_at and updated_at timestamp columns, which are automatically updated.
87
In a Schema::create closure, how would we indicate we wanted to create a column called name of type Varchar?
$table->string('name');
88
In a Schema:create closure, how would we indicate that we wanted to create a column called description that is of type TEXT?
$table->text('description');
89
How do we trigger a migration (to create a new table)?
php artisan migrate
90
If you execute the command to create a migration (databse table) and it's the first time running it, what else is created?
The migration table which contains information used for rolling back / forward stuff.
91
If you create three migrations and run them all under one command, what happens when you want to roll back one of them?
These are all treated as part of the same batch, and so rolling back one will require rolling back all of them.
92
What command do you run to rollback a migration?
php artisan migrate:rollback
93
How do you add a column to a table via migrations?
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
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)
php artisan make:migration create_todolist_table
95
In the migration file - how would you specify a new column to be added at a certain location within the database?
Use the after method. $table->string('foobar', 100)->after('id'); 100 is the length.
96
How do you determine the status of current migrations?
php artisan migrate:status
97
Laravel models are POPO's. What's a POPO?
Plain old PHP object.
98
What is the convention for creating a getter on a model?
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
What is the difference between an Accessor and a Virtual Accessor?
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
If you are using PsySH (via tinker) - what do you have to do before playing with amodel?
You must declare the namespace >>> namespace Todoparrot; => null >>> $list = User::find(1); >>> echo $list->fullname;
101
When do you use a mutator?
When you want to modify the value of an attribute. NOTE: These are also known as 'setters'
102
Laravel recognises mutators when they are set with which convention?
setAttributeNameAttribute i.e. for an attribute with the AttributeName of password setPasswordAttribute($password) - But you call it like this: $user->password = 'blah';
103
How do you stay... DRY?
Don't Repeat Yourself | i.e. use lots of custom methods to keep extra code out of controllers
104
Is model based data validation (laravel style) used in all cases?
No - it's not necessary for form validation - you can use a form requests feature from Laravel 5 for that.
105
How do you setup rule validation within a model?
You create an array called rules - where the rules are configured. private $rules = [ 'name' => 'required', 'email' => 'required | email | unique:users' ];
106
How do we setup the validation logic for a model?
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
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?
You must define the protected '$fillable' property of the model. It is an array of attribute names from the model.
108
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?
You can use the 'guarded' attribute. protected $guarded = ['name', 'description']; Works the reverse of $fillable.
109
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?
You need to setup a route in the routes.php file Route::resource('lists', 'ListsController');
110
Where is the routes file in Laravel 5?
app/Http/routes.php
111
What is the difference between setting up a straight forward route for a GET request and a RESTful route?
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
How can you use the model to get the total count of all elements in the table?
echo Todolist::all()->count();
113
Laravel's blade templating engine exposes the PHP objects as what?
Simple PHP objects - you can just use normal PHP notation to get access to the variables / values.
114
What command is used to seed the database?
php artisan db:seed
115
What file does the db:seed command execute?
database/seeds/DatabaseSeeder.php
116
Where are the seed files located?
database/seeds
117
When you've created a database seed file, what is the one step you'll have to do before running the seeder?
``` Rebuild the class map composer dump-autoload ```
118
How do you rebuild the class map using composer?
composer dump-autoload
119
How would you use the DB class to remove a table?
DB::table('foobar')->delete();
120
What library (included with 5.1 by default) can be used to generate large amounts of test data?
Faker
121
What does the command Todolist::truncate() do?
Deletes all of the records in the Todolist model.
122
If we see a variable like such: $lists = Todolist::all() we know it is of type....
Illuminate\Database\Eloquent\Collection
123
The Collection class is...
iterable
124
What is one way we can access the data within an iterable class?
``` foreach($lists as $list) { // Do stuff } ```
125
Rather than using PHP's foreach method to iterate through an Eloquent collection, what is the other option?
$lists = todoparrot\Todolist::all(); $lists->each(function($list){ echo $list->name; }); This is the Eloquent method of iteration.
126
Rather than using a collections "all" method to obtain all of the data, how would you retrieve an individual record using the ID?
$list = Todolist::find(3);
127
Where do error views live?
resources/views/errors
128
Where do we put our custom exception handlers?
app/Exceptions/Handler.php
129
If you get the following error, what should you potentially check for? No query results for model [todoparrot\Todolist].
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
For performance reasons it's best not to retrieve all fields on a table - how do you restrict this in code?
Use select | Todolist::select('name', 'description')->first()
131
How can you get a count of the records selected in a Eloquent collection from within the blade?
{{ $lists->count() }}
132
How can you order records?
$lists = Todolist::orderby('name')->get();
133
When do you use the ->get() method?
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
What is the Laravel default sort order?
Ascending
135
How do you change the sort order of a query?
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
How would you order results when multiple columns are involved?
You can specify the order on each column $lists = Todolist:orderby('created_at', 'DESC') - >orderby('name', 'ASC') - >get();
137
How could you select all of the lists in a class called Todolist, that had the field 'completed' set to true?
$lists = Todolist::where('completed', '=', 1)->get();
138
What is the Laravel safeguard against SQL injection when using the 'where' method?
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
What is the whereRaw interface for?
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
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
$lists = Todolist::select(DB::raw('year(created_at) as year'), DB::raw('count(name) as `count`')) - >groupBy('year') - >orderBy('`count` desc')->get();
141
What is DB:raw?
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
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?
->having('year', '>', '2010')->get() Much like MySQL - you would use the having function for this kind of query
143
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
$lists = Todolists::take(5)->skip(5)->orderBy('created_at', 'desc')->get();
144
How would you retrieve the first item in a model?
$list = Todolist::orderBy('created_by', 'desc')->first()
145
You use the first() method to get the first element in a list - how do you get the last?
You also use 'first()' - but you reverse the sort order to get the last item: $list = Todolist::orderBy('created_by', 'asc')->first()
146
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);
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
Why is the following method efficient? $exists = Todolist::where('name', '=', 'San Juan')->exists();
Because it doesn't retrieve the record in order to determine whether it exists.
148
How do you use pagination?
$list = Todolist::orderby('created_at')->pagination(10);
149
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?
You need to embed the pagination navigation - in a blade you use: {!! $lists->render() !!}
150
How would you create a new record using the 'save' method?
$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
What is the alternative to the 'save' method when creating a new database object?
The create method - it creates and saves in one call. $list = Todolist::create( array('name' => 'San Juan Vacation', 'description' => 'Fun times' );
152
How would you retrieve a model instance or create a new one if it doesn't exist?
$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
How would you update a model instance or create a new one if it doesn't exist?
$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
How do you delete a record?
$list = Todolist::find(12); $list->delete(); or $list->destroy(12); which consolidates the above commands.
155
How do you redirect to a named route?
return \Redirect::route('login');
156
What is a soft delete?
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
How do you setup soft deletes in Laravel?
In the migrate file: Schema::table('todolists', function(Blueprint $table) { $table->softDeletes(); });
158
What has to happen in the model to enable soft deleteing?
Include the softDeletes trait. ``` use Illumate\Database\Eloquent\SoftDeletes; class TodoList extends Model { use SoftDeletes; protected $data = ['deleted_at']; } ```
159
By providing a date attribute in the following format, it forces Laravel to store the dates as type... protected $data = ['deleted_at'];
Carbon
160
If a record has been soft deleted, how do you go about finding it?
$list = Todolist::withTrashed()->get();
161
How do we get all of the records through the Laravel builder interface?
$lists = DB::table('todolists')->get(); Returns a group of objects of type stdClass
162
How do you find a specific record when using the Laravel builder class?
$list = DB::table('todolists')->find(52);
163
How would you get just the name column of a table?
$lists = DB::table('todolists')->select('name')->get();
164
How would you use the Laravel builder class to execute raw SQL?
$lists = DB::select('SELECT * FROM todolists');
165
What laravel builder method would you use to delete an element with raw SQL?
DB::delete('delete from todolists where completed = 1');
166
What laravel builder method would you use to update an element with raw SQL?
DB::update('update todolists set completed = 1 where id = ?', array(52));
167
What laravel builder method would you use to insert an element with raw SQL?
DB::insert('insert into todolists (name, description) values (?, ?)', array('superman', 'cocksniff'));
168
If you want to run an administrative command, or a command that doesn't interact directly with the actual database - what would you use?
$lists = DB::statement('drop table todolists');
169
What package can be used to create sluggable models?
Cviebrock/eloquent-sluggable
170
If you are using PHPUnit for testing - how do you override the Laravel database settings so that you can use a specific test database?
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
What is the best way to make sure the PHPUnit tests you are doing are consistent and maintain integrity?
Tear down and rebuild the database before each set of tests so you are working with known data.
172
How do you make your PHPUnit tests dump / rebuild the databases before running tests?
Add the trait DatabaseMigrations. use DatabaseMigrations;
173
How do you setup a model factory so that it can be used to generate data in the test suites?
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
What is the difference between the following commands? factory('App\Todolist')->create(); factory('App\Todolist')->make();
create() actually creates data in the database. Make() will simply create the Todolist object which is local to the test.
175
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?
make() - it doesn't hit the database and thus is faster.
176
How would you write a PHPUnit test to test whether a particular class could be instantiated correctly?
$list = new Todolist; | $this->assertEquals(get_class($list), 'todoparrot\Todolist');
177
When specifying an integer column as a foreign key, what must you remember to do?
You MUST declare it as unsigned or else the migration will fail.
178
How do you formalise a one-to-one relationship with two classes in laravel?
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
How would you access a user's telephone number (which exists in their profile) using the one-to-one relationship?
$user = User::find(212)->profile->telephone
180
How do you create a one to one relationship?
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
What happens if you delete a user that has an associated profile?
You can't have a profile on it's own, so it must be deleted. $user = User::find(212); $user->profile()->delete();
182
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?
When creating the migration - make sure you use the onDelete('cascade') option: $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
183
The hasOne relationship is a ... way definition?
one way - i.e. you can get a profile from a user, but you can't get a user from a profile.
184
How do you create a two way relationship between two models?
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
If table B has a foreign key that links to table A - what kind of relationship does this imply?
A "belongs to" relationship - i.e. Table B belongs to Table A.
186
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');
Because this table expects to reference the other table ("todolists") - Laravel will make sure the "todolist_id" field on this table is indexed.
187
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'?
$completedTasks = Todolist::find(1)->tasks()->where('done', true)->get();
188
What is the intermediary table called that links two tables in a many to many relationship?
A pivot table
189
What does Laravel assume about pivot table naming?
That it is named by concatenating the two related tables together with an underscore.
190
If we have Todolist and Category with a many to many relationship - how will the pivot table be named?
category_todolist The name is in alphabetical order, and laravel assumes underscores.
191
What does the "withTimestamps()" method do here? return $this->belongsToMany('todoparrot\Category')->withTimestamps();
It updates the "updated_at / created_at" fields on a table (as long as they exist). This is particularly used with pivot tables.
192
How do you associate records in a many to many situation?
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); ```