Dataset Viewer
instruction
stringlengths 28
119
| input
stringlengths 115
3.33k
| output
stringlengths 82
10.8k
| tags
listlengths 4
10
| source_url
stringlengths 71
123
| category
stringclasses 1
value |
---|---|---|---|---|---|
How do I get the query builder to output its raw SQL query as a string?
|
Given the following code:
DB::table('users')->get();
I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be
SELECT * FROM users
.
How do I do this?
|
Use the
toSql()
method on a
QueryBuilder
instance.
DB::table('users')->toSql()
would return:
select * from `users`
This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you're building it.
Note: This method works for query builder or Eloquent, however
toSql()
is used instead of
first()
or
get()
. You cannot run the query and also get the SQL at the same time using this method.
|
[
"php",
"sql",
"laravel",
"eloquent",
"laravel-query-builder",
"php",
"sql",
"laravel",
"eloquent",
"laravel-query-builder"
] |
https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string
|
Laravel Q&A
|
How can I remove a package from Laravel using PHP Composer?
|
What is the correct way to remove a package from Laravel using PHP Composer?
So far I've tried:
Remove declaration from file
composer.json
(in the "require" section)
Remove any
class aliases
from file
app.php
Remove any references to the package from my code :-)
Run
composer update
Run
composer dump-autoload
None of these options are working! What am I missing?
|
Composer 1.x and 2.x
Running the following command will remove the package from vendor (or wherever you install packages),
composer.json
and
composer.lock
. Change vendor/package appropriately.
composer remove vendor/package
Obviously you'll need to remove references to that package within your app.
I'm currently running the following version of Composer:
Composer version 1.0-dev (7b13507dd4d3b93578af7d83fbf8be0ca686f4b5) 2014-12-11 21:52:29
Documentation
https://getcomposer.org/doc/03-cli.md#remove-rm-uninstall
Updates
18/10/2024 - Updated URL to
remove-rm-uninstall
documentation
27/12/2023 - Fixed URL to
remove-rm
documentation
26/10/2020 - Updated answer to assert command works for v1.x and v2.x of Composer
|
[
"php",
"laravel",
"composer-php",
"uninstallation",
"package-managers",
"php",
"laravel",
"composer-php",
"uninstallation",
"package-managers"
] |
https://stackoverflow.com/questions/23126562/how-can-i-remove-a-package-from-laravel-using-php-composer
|
Laravel Q&A
|
How to create custom helper functions in Laravel
|
I would like to create helper functions to avoid repeating code between views in Laravel. For example:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
They're basically text formatting functions. How should I define globally available helper functions like
fooFormatText()
?
|
Create a
helpers.php
file in your app folder and load it up with composer:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},
After adding that to your
composer.json
file, run the following command:
composer dump-autoload
If you don't like keeping your
helpers.php
file in your
app
directory (because it's not a PSR-4 namespaced class file), you can do what the
laravel.com
website does: store the
helpers.php
in the bootstrap directory
. Remember to set it in your
composer.json
file:
"files": [
"bootstrap/helpers.php"
]
Example:
Create
helpers.php
in the app directory with name
app/helpers.php
:
<?php
if (!function_exists('testHelperFunction')) {
function testHelperFunction()
{
return "Hello, World!";
}
}
|
[
"php",
"laravel",
"laravel-8",
"laravel-blade",
"laravel-helper",
"php",
"laravel",
"laravel-8",
"laravel-blade",
"laravel-helper"
] |
https://stackoverflow.com/questions/28290332/how-to-create-custom-helper-functions-in-laravel
|
Laravel Q&A
|
How to Create Multiple Where Clause Query Using Laravel Eloquent?
|
I'm using the Laravel Eloquent query builder and I have a query where I want a
WHERE
clause on multiple conditions. It works, but it's not elegant.
Example:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();
Is there a better way to do this, or should I stick with this method?
|
In
Laravel 5.3
(and still true as of
7.x
) you can use more granular wheres passed as an array:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
Personally I haven't found use-case for this over just multiple
where
calls, but fact is you can use it.
Since June 2014 you can pass an array to
where
As long as you want all the
wheres
use
and
operator, you can group them this way:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
Then:
$results = User::where($matchThese)->get();
// with another group
$results = User::where($matchThese)
->orWhere($orThose)
->get();
The above will result in such query:
SELECT * FROM users
WHERE (field = value AND another_field = another_value AND ...)
OR (yet_another_field = yet_another_value AND ...)
|
[
"php",
"laravel",
"eloquent",
"laravel-query-builder",
"php",
"laravel",
"eloquent",
"laravel-query-builder"
] |
https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent
|
Laravel Q&A
|
Rollback one specific migration in Laravel
|
I want
to rollback only :
Rolled back: 2015_05_15_195423_alter_table_web_directories
I run
php artisan migrate:rollback
, 3 of my migration are rolling back.
Rolled back: 2015_05_15_195423_alter_table_web_directories
Rolled back: 2015_05_13_135240_create_web_directories_table
Rolled back: 2015_05_13_134411_create_contacts_table
I delete
both of my
web_directories
and my
contacts
table unintentionally. I never want that to happen, and if I can rollback only that specific one, this disaster will never happen.
|
Laravel 5.3+
Rollback one step. Natively.
php artisan migrate:rollback --step=1
And here's the manual page:
docs
.
Laravel 5.2 and before
No way to do without some hassle. For details, check Martin Bean's
answer
.
|
[
"laravel",
"laravel-4",
"laravel-5",
"database-migration",
"laravel",
"laravel-4",
"laravel-5",
"database-migration"
] |
https://stackoverflow.com/questions/30287896/rollback-one-specific-migration-in-laravel
|
Laravel Q&A
|
Laravel Add a new column to existing table in a migration
|
I can't figure out how to add a new column to my existing database table using the Laravel framework.
I tried to edit the migration file using...
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
In terminal, I execute
php artisan migrate:install
and
migrate
.
How do I add new columns?
|
To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
for Laravel 3:
php artisan migrate:make add_paid_to_users
You then need to use the
Schema::table()
method (as you're accessing an existing table, not creating a new one). And you can add a column like this:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
and don't forget to add the rollback option:
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('paid');
});
}
Then you can run your migrations:
php artisan migrate
This is all well covered in the documentation for both Laravel 4 / Laravel 5:
Schema Builder
Migrations
And for Laravel 3:
Schema Builder
Migrations
Edit:
use
$table->integer('paid')->after('whichever_column');
to add this field after specific column.
applicable for MySQL only
|
[
"php",
"laravel",
"laravel-migrations",
"php",
"laravel",
"laravel-migrations"
] |
https://stackoverflow.com/questions/16791613/laravel-add-a-new-column-to-existing-table-in-a-migration
|
Laravel Q&A
|
PDOException SQLSTATE[HY000] [2002] No such file or directory
|
I believe that I've successfully deployed my (very basic) site to fortrabbit, but as soon as I connect to SSH to run some commands (such as
php artisan migrate
or
php artisan db:seed
) I get an error message:
[PDOException]
SQLSTATE[HY000] [2002] No such file or directory
At some point the migration must have worked, because my tables are there - but this doesn't explain why it isn't working for me now.
|
One of simplest reasons for this error is that a MySQL server is not running. So verify that first. In case it's up, proceed to other recommendations:
Laravel 4:
Change "host" in the
app/config/database.php
file from "localhost" to "127.0.0.1"
Laravel 5+:
Change "DB_HOST" in the
.env
file from "localhost" to "127.0.0.1"
I had the exact same problem. None of the above solutions worked for me. I solved the problem by changing the "host" in the /app/config/database.php file from "localhost" to "127.0.0.1".
Not sure why "localhost" doesn't work by default but I found this answer in a similar question solved in a symfony2 post.
https://stackoverflow.com/a/9251924
Update:
Some people have asked as to why this fix works so I have done a little bit of research into the topic. It seems as though they use different connection types as explained in this post
https://stackoverflow.com/a/9715164
The issue that arose here is that "localhost" uses a UNIX socket and can not find the database in the standard directory. However "127.0.0.1" uses TCP (Transmission Control Protocol), which essentially means it runs through the "local internet" on your computer being much more reliable than the UNIX socket in this case.
|
[
"php",
"mysql",
"laravel",
"database",
"pdo",
"php",
"mysql",
"laravel",
"database",
"pdo"
] |
https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory
|
Laravel Q&A
|
Laravel requires the Mcrypt PHP extension
|
I am trying to use the
migrate
function in Laravel 4 on OSX. However, I am getting the following error:
Laravel requires the Mcrypt PHP extension.
As far as I understand, it's already enabled (see the image below).
What is wrong, and how can I fix it?
|
Do you have
MAMP
installed?
Use
which php
in the terminal to see which version of PHP you are using.
If it's not the PHP version from MAMP, you should edit or add
.bash_profile
in the user's home directory, that is :
cd ~
In
.bash_profile
, add following line:
export PATH=/Applications/MAMP/bin/php/php5.4.10/bin:$PATH
Edited:
First you should use command
cd /Applications/MAMP/bin/php
to check which PHP version from MAMP you are using and then replace with the PHP version above.
Then
restart
the terminal to see which PHP you are using now.
And it should be working now.
|
[
"php",
"laravel",
"laravel-4",
"mcrypt",
"php",
"laravel",
"laravel-4",
"mcrypt"
] |
https://stackoverflow.com/questions/16830405/laravel-requires-the-mcrypt-php-extension
|
Laravel Q&A
|
No Application Encryption Key Has Been Specified
|
I'm trying to use the
Artisan
command like this:
php artisan serve
It displays:
Laravel development server started:
http://127.0.0.1:8000
However, it won't automatically launch and when I manually enter
http://127.0.0.1:8000
it shows this error:
RuntimeException No application encryption key has been specified.
What's the cause of this problem, and how can it be fixed?
I'm using
Laravel framework 5.5-dev
.
|
From
Encryption - Laravel - The PHP Framework For Web Artisans
:
Before using Laravel's encrypter, you must set a key option in your
config/app.php configuration file. You should use the
php artisan key:generate
command to generate this key
I found it using this query in google.com:
"laravel add encrption key"
(Yes, it worked even with the typo!)
Note that if the
.env
file contains the key but you are still getting an application key error, then run
php artisan config:cache
to clear and reset the config.
|
[
"php",
"laravel",
"laravel-5",
"laravel-artisan",
"php",
"laravel",
"laravel-5",
"laravel-artisan"
] |
https://stackoverflow.com/questions/44839648/no-application-encryption-key-has-been-specified
|
Laravel Q&A
|
Displaying HTML with Blade shows the HTML code
|
I have a string returned to one of my views, like this:
$text = '<p><strong>Lorem</strong> ipsum dolor <img src="images/test.jpg"></p>'
I'm trying to display it with Blade:
{{$text}}
However, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel?
PS. PHP
echo()
displays the HTML correctly.
|
You need to use
{!! $text !!}
The string will auto escape when using
{{ $text }}
.
|
[
"php",
"html",
"laravel",
"laravel-blade",
"php",
"html",
"laravel",
"laravel-blade"
] |
https://stackoverflow.com/questions/29253979/displaying-html-with-blade-shows-the-html-code
|
Laravel Q&A
|
How to set up file permissions for Laravel?
|
I'm using Apache Web Server that has the owner set to
_www:_www
. I never know what is the best practice with file permissions, for example when I create new Laravel 5 project.
Laravel 5 requires
/storage
folder to be writable. I found plenty of different approaches to make it work and I usually end with making it
777
chmod recursively. I know it's not the best idea though.
The official doc says:
Laravel may require some permissions to be configured: folders within
storage
and
vendor
require write access by the web server.
Does it mean that the web server needs access to the
storage
and
vendor
folders themselves too or just their current contents?
I assume that what is much better, is changing the
owner
instead of permissions. I changed all Laravel's files permissions recursively to
_www:_www
and that made the site work correctly, as if I changed chmod to
777
. The problem is that now my text editor asks me for password each time I want to save any file and the same happens if I try to change anything in Finder, like for example copy a file.
What is the correct approach to solve these problems?
Change
chmod
Change the owner of the files to match those of the
web server and perhaps set the text editor (and Finder?) to skip
asking for password, or make them use
sudo
Change the owner of the web server to match the os user (I don't
know the consequences)
Something else
|
Just to state the obvious for anyone viewing this discussion.... if you give any of your folders 777 permissions, you are allowing ANYONE to read, write and execute any file in that directory.... what this means is you have given ANYONE (any hacker or malicious person in the entire world) permission to upload ANY file, virus or any other file, and THEN execute that file...
IF YOU ARE SETTING YOUR FOLDER PERMISSIONS TO 777 YOU HAVE OPENED YOUR
SERVER TO ANYONE THAT CAN FIND THAT DIRECTORY. Clear enough??? :)
There are basically two ways to setup your ownership and permissions. Either you give yourself ownership or you make the webserver the owner of all files.
Webserver as owner (the way most people do it, and the Laravel doc's way):
assuming www-data (it could be something else) is your webserver user.
sudo chown -R www-data:www-data /path/to/your/laravel/root/directory
if you do that, the webserver owns all the files, and is also the group, and you will have some problems uploading files or working with files via FTP, because your FTP client will be logged in as you, not your webserver, so add your user to the webserver user group:
sudo usermod -a -G www-data ubuntu
Of course, this assumes your webserver is running as www-data (the Homestead default), and your user is ubuntu (it's vagrant if you are using Homestead).
Then you set all your directories to 755 and your files to 644...
SET file permissions
sudo find /path/to/your/laravel/root/directory -type f -exec chmod 644 {} \;
SET directory permissions
sudo find /path/to/your/laravel/root/directory -type d -exec chmod 755 {} \;
Your user as owner
I prefer to own all the directories and files (it makes working with everything much easier), so, go to your laravel root directory:
cd /var/www/html/laravel >> assuming this is your current root directory
sudo chown -R $USER:www-data .
Then I give both myself and the webserver permissions:
sudo find . -type f -exec chmod 664 {} \;
sudo find . -type d -exec chmod 775 {} \;
Then give the webserver the rights to read and write to storage and cache
Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache and any other directories the webserver needs to upload or write too (depending on your situation), so run the commands from bashy above :
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
Now, you're secure and your website works, AND you can work with the files fairly easily
|
[
"php",
"apache",
"laravel",
"laravel-5",
"file-permissions",
"php",
"apache",
"laravel",
"laravel-5",
"file-permissions"
] |
https://stackoverflow.com/questions/30639174/how-to-set-up-file-permissions-for-laravel
|
Laravel Q&A
|
Laravel Eloquent Query: Using WHERE with OR AND OR?
|
How do I say
WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)
For more complicated queries am I supposed to use raw SQL?
|
Make use of
Logical Grouping
(Laravel
7.x
/
4.2
). For your example, it'd be something like this:
Model::where(function ($query) {
$query->where('a', '=', 1)
->orWhere('b', '=', 1);
})->where(function ($query) {
$query->where('c', '=', 1)
->orWhere('d', '=', 1);
});
|
[
"php",
"laravel",
"eloquent",
"laravel-query-builder",
"php",
"laravel",
"eloquent",
"laravel-query-builder"
] |
https://stackoverflow.com/questions/16995102/laravel-eloquent-query-using-where-with-or-and-or
|
Laravel Q&A
|
Get the Last Inserted Id Using Laravel Eloquent
|
I'm currently using the below code to insert data in a table:
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
I want to return the last ID inserted but I don't know how to get it.
Kind regards!
|
After
save
,
$data->id
should be the last id inserted.
$data->save();
$data->id;
Can be used like this.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try this
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
|
[
"php",
"database",
"laravel",
"eloquent",
"php",
"database",
"laravel",
"eloquent"
] |
https://stackoverflow.com/questions/21084833/get-the-last-inserted-id-using-laravel-eloquent
|
Laravel Q&A
|
Laravel Checking If a Record Exists
|
I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if
$user
has a record?
|
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
|
[
"php",
"laravel",
"laravel-5",
"eloquent",
"conditional-statements",
"php",
"laravel",
"laravel-5",
"eloquent",
"conditional-statements"
] |
https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists
|
Laravel Q&A
|
Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
|
I've found the concept and meaning behind these methods to be a little confusing, is it possible for somebody to explain to me what the difference between
has
and
with
is, in the context of an example (if possible)?
|
With
with()
is for
eager loading
. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
Has
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use
has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas()
works basically the same as
has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
|
[
"laravel",
"orm",
"eloquent",
"relational-database",
"relationship"
] |
https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean
|
Laravel Q&A
|
Could not open input file: artisan
|
When trying to create a new laravel project, The following error appears on the CLI:
Could not open input file: artisan
Script php artisan clear-compiled handling the post-install-cmd event returned with an error
I am using the latest version of XAMPP v3.2.1 with PHP 5.5.15 and with mcrypt enabled (made sure of that by issuing the command php -m). And I am running windows 8.1
|
You need to first
create Laravel project
and if you already have one you need to go to this project dir using
cd
command in terminal for example
cd myproject
.
Now you will be able to run any artisan commands, for example running
php artisan
will display you list of available commands.
|
[
"php",
"laravel",
"laravel-4",
"laravel-artisan",
"php",
"laravel",
"laravel-4",
"laravel-artisan"
] |
https://stackoverflow.com/questions/26193314/could-not-open-input-file-artisan
|
Laravel Q&A
|
How to query all the GraphQL type fields without writing a long query?
|
Assume you have a GraphQL type and it includes many fields.
How to query all the fields without writing down a long query that includes the names of all the fields?
For example, If I have these fields :
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The id of the user'
],
'username' => [
'type' => Type::string(),
'description' => 'The email of user'
],
'count' => [
'type' => Type::int(),
'description' => 'login count for the user'
]
];
}
To query all the fields usually the query is something like this:
FetchUsers{users(id:"2"){id,username,count}}
But I want a way to have the same results without writing all the fields, something like this:
FetchUsers{users(id:"2"){*}}
//or
FetchUsers{users(id:"2")}
Is there a way to do this in GraphQL ??
I'm using
Folkloreatelier/laravel-graphql
library.
|
Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.
|
[
"php",
"laravel",
"graphql",
"graphql-php",
"php",
"laravel",
"graphql",
"graphql-php"
] |
https://stackoverflow.com/questions/34199982/how-to-query-all-the-graphql-type-fields-without-writing-a-long-query
|
Laravel Q&A
|
Laravel - Eloquent or Fluent random row
|
How can I select a random row using Eloquent or Fluent in Laravel framework?
I know that by using SQL, you can do order by RAND(). However, I would like to get the random row
without
doing a count on the number of records prior to the initial query.
Any ideas?
|
Laravel >= 5.2:
User::inRandomOrder()->get();
or to get the specific number of records
// 5 indicates the number of records
User::inRandomOrder()->limit(5)->get();
// get one random record
User::inRandomOrder()->first();
or using the
random
method for collections:
User::all()->random();
User::all()->random(10); // The amount of items you wish to receive
Laravel 4.2.7 - 5.1:
User::orderByRaw("RAND()")->get();
Laravel 4.0 - 4.2.6:
User::orderBy(DB::raw('RAND()'))->get();
Laravel 3:
User::order_by(DB::raw('RAND()'))->get();
Check
this article
on MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using
RAW Queries
.
edit 1:
As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since
this
change. I updated my answer accordingly.
edit 2:
Laravel 5.2 finally implements
a wrapper function
for this. It's called
inRandomOrder()
.
|
[
"php",
"laravel",
"random",
"eloquent",
"fluent",
"php",
"laravel",
"random",
"eloquent",
"fluent"
] |
https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row
|
Laravel Q&A
|
How to use multiple databases in Laravel
|
I want to combine multiple databases in my system. Most of the time the database is MySQL; but it may differ in future i.e. Admin can generate such a reports which is
use source of heterogeneous
database system.
So my question is
does Laravel provide any Facade
to deal with such situations? Or any other framework have more suitable capabilities for problem is?
|
From Laravel Docs
: You may access each connection via the connection method on the
DB
facade when using multiple connections. The name passed to the connection method should correspond to one of the connections listed in your
config/database.php
configuration file:
$users = DB::connection('foo')->select(...);
Define Connections
Using
.env
>= 5.0 (or higher)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mysql_database
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_PGSQL=pgsql
DB_HOST_PGSQL=127.0.0.1
DB_PORT_PGSQL=5432
DB_DATABASE_PGSQL=pgsql_database
DB_USERNAME_PGSQL=root
DB_PASSWORD_PGSQL=secret
Using
config/database.php
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'pgsql' => [
'driver' => env('DB_CONNECTION_PGSQL'),
'host' => env('DB_HOST_PGSQL'),
'port' => env('DB_PORT_PGSQL'),
'database' => env('DB_DATABASE_PGSQL'),
'username' => env('DB_USERNAME_PGSQL'),
'password' => env('DB_PASSWORD_PGSQL'),
],
Note:
In
pgsql
, if
DB_username
and
DB_password
are the same, then you can use
env('DB_USERNAME')
, which is mentioned in
.env
first few lines.
Without
.env
<= 4.0 (or lower)
app/config/database.php
return array(
'default' => 'mysql',
'connections' => array(
# Primary/Default database connection
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'mysql_database',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Secondary database connection
'pgsql' => [
'driver' => 'pgsql',
'host' => 'localhost',
'port' => '5432',
'database' => 'pgsql_database',
'username' => 'root',
'password' => 'secret',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]
),
);
Schema / Migration
Run the
connection()
method to specify which connection to use.
Schema::connection('pgsql')->create('some_table', function($table)
{
$table->increments('id'):
});
Or, at the top, define a connection.
protected $connection = 'pgsql';
Query Builder
$users = DB::connection('pgsql')->select(...);
Model
(In Laravel >= 5.0 (or higher))
Set the
$connection
variable in your model
class ModelName extends Model { // extend changed
protected $connection = 'pgsql';
}
Eloquent
(In Laravel <= 4.0 (or lower))
Set the
$connection
variable in your model
class SomeModel extends Eloquent {
protected $connection = 'pgsql';
}
Transaction Mode
DB::transaction(function () {
DB::connection('mysql')->table('users')->update(['name' => 'John']);
DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
});
or
DB::connection('mysql')->beginTransaction();
try {
DB::connection('mysql')->table('users')->update(['name' => 'John']);
DB::connection('pgsql')->beginTransaction();
DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
DB::connection('pgsql')->commit();
DB::connection('mysql')->commit();
} catch (\Exception $e) {
DB::connection('mysql')->rollBack();
DB::connection('pgsql')->rollBack();
throw $e;
}
You can also define the connection at runtime via the
setConnection
method or the
on
static method:
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('pgsql'); // non-static method
$something = $someModel->find(1);
$something = SomeModel::on('pgsql')->find(1); // static method
return $something;
}
}
Note:
Be careful about building relationships with tables across databases! It is possible to do, but it can come with caveats depending on your database and settings.
Tested versions (
Updated
)
Version
Tested (Yes/No)
4.2
No
5
Yes (5.5)
6
No
7
No
8
Yes (8.4)
9
Yes (9.2)
Useful Links
Laravel 5 multiple database connections FROM
laracasts.com
Connect multiple databases in Laravel FROM
tutsnare.com
Multiple DB Connections in Laravel FROM
fideloper.com
|
[
"php",
"mysql",
"laravel",
"database",
"php",
"mysql",
"laravel",
"database"
] |
https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel
|
Laravel Q&A
|
How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?
|
I am using Laravel 4. I would like to access the current URL inside an
@if
condition in a view using the Laravel's Blade templating engine but I don't know how to do it.
I know that it can be done using something like
<?php echo URL::current(); ?>
but It's not possible inside an
@if
blade statement.
Any suggestions?
|
You can use:
Request::url()
to obtain the current URL, here is an example:
@if(Request::url() === 'your url here')
// code
@endif
Laravel offers a method to find out, whether the URL matches a pattern or not
if (Request::is('admin/*'))
{
// code
}
Check the related documentation to obtain different request information:
http://laravel.com/docs/requests#request-information
|
[
"laravel",
"laravel-4",
"laravel-blade",
"laravel",
"laravel-4",
"laravel-blade"
] |
https://stackoverflow.com/questions/17591181/how-to-get-the-current-url-inside-if-statement-blade-in-laravel-4
|
Laravel Q&A
|
How to fix Error: laravel.log could not be opened?
|
I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some reason I keep getting this error (I haven't even started coding yet)
Error in exception handler: The stream or file "/var/www/laravel/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/laravel/bootstrap/compiled.php:8423
I've read this has something to do with permissions but
chmod -R 775 storage
didn't help at all.
|
Never set a directory to 777
. you should change directory ownership. so set your current user that you are logged in with as owner and the webserver user (www-data, apache, ...) as the group.
You can try this:
sudo chown -R $USER:www-data storage
sudo chown -R $USER:www-data bootstrap/cache
then to set directory permission try this:
chmod -R 775 storage
chmod -R 775 bootstrap/cache
Update:
Webserver user and group depend on your webserver and your OS. to figure out what's your web server user and group use the following commands. for nginx use:
ps aux|grep nginx|grep -v grep
for apache use:
ps aux | egrep '(apache|httpd)'
|
[
"php",
"laravel",
"permission-denied",
"php",
"laravel",
"permission-denied"
] |
https://stackoverflow.com/questions/23411520/how-to-fix-error-laravel-log-could-not-be-opened
|
Laravel Q&A
|
Eloquent Collection: Counting and Detect Empty
|
This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from
$result = Model::where(...)->get()
is empty, as well as counting the number of elements.
We are currently using
!$result
to detect empty result, is that sufficient? As for
count($result)
, does it actually cover all cases, including empty result?
|
When using
->get()
you cannot simply use any of the below:
if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you
dd($result);
you'll notice an instance of
Illuminate\Support\Collection
is always returned, even when there are no results. Essentially what you're checking is
$a = new stdClass; if ($a) { ... }
which will always return true.
To determine if there are any results you can do any of the following:
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
You could also use
->first()
instead of
->get()
on the query builder which will return an instance of the first found model, or
null
otherwise. This is useful if you need or are expecting only one result from the database.
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
->first()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_first
isEmpty()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
->count()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
count($result)
works because the Collection implements
Countable
and an internal
count()
method:
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
Bonus Information
The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like
->all()
->first()
->lists()
and others). Those methods
also
exist on the
Collection
object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing
var_dump(User::all())
and experimenting to see what classes it's actually returning (with help of
get_class(...)
). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.
Laravel 5.2 Collection Class
Laravel 5.2 Query Builder
|
[
"laravel",
"laravel-4",
"eloquent",
"laravel-collection",
"laravel",
"laravel-4",
"eloquent",
"laravel-collection"
] |
https://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty
|
Laravel Q&A
|
How to Set Variables in a Laravel Blade Template
|
I'm reading the Laravel Blade
documentation
and I can't figure out how to assign variables inside a template for use later. I can't do
{{ $old_section = "whatever" }}
because that will echo "whatever" and I don't want that.
I understand that I can do
<?php $old_section = "whatever"; ?>
, but that's not elegant.
Is there a better, elegant way to do that in a Blade template?
|
EASY WAY
If you want to define multiple variables, use the full form of the blade directive:
@php
$i = 1;
$j = 2;
@endphp
If you only want to define one variable, you can also use a single PHP statement:
@php($i = 1)
MORE ADVANCED: ADD A 'DEFINE' TAG
If you want to use custom tags and use a @define instead of @php, extend Blade like this:
/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| @define $variable = "whatever"
| </code>
|--------------------------------------------------------------------------
*/
\Blade::extend(function($value) {
return preg_replace('/\@define(.+)/', '<?php ${1}; ?>', $value);
});
Then do one of the following:
Quick solution
: If you are lazy, just put the code in the boot() function of the AppServiceProvider.php.
Nicer solution
:
Create an own service provider. See
https://stackoverflow.com/a/28641054/2169147
on how to extend blade in Laravel 5. It's a bit more work this way, but a good exercise on how to use Providers :)
After the above changes, you can use:
@define $i = 1
to define a variable.
|
[
"php",
"laravel",
"laravel-blade",
"laravel-4",
"blade",
"blade",
"php",
"laravel",
"laravel-blade"
] |
https://stackoverflow.com/questions/13002626/how-to-set-variables-in-a-laravel-blade-template
|
Laravel Q&A
|
"Please provide a valid cache path" error in laravel
|
I duplicated a working laravel app and renamed it to use for another app. I deleted the vendor folder and run the following commands again:
composer self-update
composer-update
npm install
bower install
I configured my routes and everything properly however now when I try to run my app in my browser I get the following errors:
InvalidArgumentException in Compiler.php line 36: Please provide a
valid cache path.
ErrorException in Filesystem.php line 111:
file_put_contents(F:\www\example\app\storage\framework/sessions/edf262ee7a2084a923bb967b938f54cb19f6b37d):
failed to open stream: No such file or directory
I have never had this issue before, I do not know what is causing it neither do I know how to fix it, I have googled online for a solution but have found none so far.
|
Try the following:
create these folders under
storage/framework:
sessions
views
cache
Now it should work
|
[
"laravel",
"laravel-5",
"laravel",
"laravel-5"
] |
https://stackoverflow.com/questions/38483837/please-provide-a-valid-cache-path-error-in-laravel
|
Laravel Q&A
|
Get Specific Columns Using “With()” Function in Laravel Eloquent
|
I have two tables,
User
and
Post
. One
User
can have many
posts
and one
post
belongs to only one
user
.
In my
User
model I have a
hasMany
relation...
public function post(){
return $this->hasmany('post');
}
And in my
post
model I have a
belongsTo
relation...
public function user(){
return $this->belongsTo('user');
}
Now I want to join these two tables using
Eloquent with()
but want specific columns from the second table. I know I can use the Query Builder but I don't want to.
When in the
Post
model I write...
public function getAllPosts() {
return Post::with('user')->get();
}
It runs the following queries...
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
But what I want is...
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
When I use...
Post::with('user')->get(array('columns'....));
It only returns the column from the first table. I want specific columns using
with()
from the second table. How can I do that?
|
This can be done one by passing a
closure
function in
with()
as second index of array
Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()
It will only select
id
and
username
from the other table.
Remember that the
primary key (id in this case) needs to be the first param
in the
$query->select()
to actually retrieve the necessary results.
|
[
"php",
"laravel",
"eloquent",
"laravel-query-builder",
"php",
"laravel",
"eloquent",
"laravel-query-builder"
] |
https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent
|
Laravel Q&A
|
Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
|
Migration error on Laravel 5.4 with
php artisan make:auth
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl e
users
add unique
users_email_unique
(
email
))
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
|
According to the
official Laravel 7.x documentation
, you can solve this quite easily.
Update your
/app/Providers/AppServiceProvider.php
to contain:
use Illuminate\Support\Facades\Schema;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
Alternatively, you may enable the
innodb_large_prefix
option for your database. Refer to your database's documentation for instructions on how to properly enable this option.
|
[
"mysql",
"laravel",
"pdo",
"laravel-5",
"laravel-5.4",
"mysql",
"laravel",
"pdo",
"laravel-5",
"laravel-5.4"
] |
https://stackoverflow.com/questions/42244541/laravel-migration-error-syntax-error-or-access-violation-1071-specified-key-wa
|
Laravel Q&A
|
Error “Target class controller does not exist” when using Laravel 8
|
Here is my controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function register(Request $request)
{
dd('aa');
}
}
As seen in the screenshot, the class exists and is in the correct place:
My
api.php
route:
Route::get('register', 'Api\RegisterController@register');
When I hit my
register
route using
Postman
, it gave me the following error:
Target class [Api\RegisterController] does not exist.
How can I fix it?
Thanks to the answers, I was able to fix it. I decided to use the fully qualified class name for this route, but there are other options as described in the answers.
Route::get('register', 'App\Http\Controllers\Api\RegisterController@register');
|
You are using Laravel 8. In a fresh install of Laravel 8, there is no namespace prefix being applied to your route groups that your routes are loaded into.
"In previous releases of Laravel, the
RouteServiceProvider
contained a
$namespace
property. This property's value would automatically be prefixed onto controller route definitions and calls to the
action
helper /
URL::action
method. In Laravel 8.x, this property is
null
by default. This means that no automatic namespace prefixing will be done by Laravel."
Laravel 8.x Docs - Release Notes
You would have to use the Fully Qualified Class Name for your Controllers when referring to them in your routes when not using the namespace prefixing.
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
// or
Route::get('/users', 'App\Http\Controllers\UserController@index');
If you prefer the old way:
App\Providers\RouteServiceProvider
:
public function boot()
{
...
Route::prefix('api')
->middleware('api')
->namespace('App\Http\Controllers') // <---------
->group(base_path('routes/api.php'));
...
}
Do this for any route groups you want a declared namespace for.
The
$namespace
property:
Though there is a mention of a
$namespace
property to be set on your
RouteServiceProvider
in the Release notes and commented in your
RouteServiceProvider
this does not have any effect on your routes. It is currently only for adding a namespace prefix for generating URLs to actions. So you can set this variable, but it by itself won't add these namespace prefixes, you would still have to make sure you would be using this variable when adding the namespace to the route groups.
This information is now in the Upgrade Guide
Laravel 8.x Docs - Upgrade Guide - Routing
With what the Upgrade Guide is showing the
important
part is that you are defining a namespace on your routes groups. Setting the
$namespace
variable by itself
only
helps in generating URLs to actions.
Again, and I can't stress this enough, the
important
part is setting the namespace for the route groups, which they just happen to be doing by referencing the member variable
$namespace
directly in the example.
Update:
If you have installed a fresh copy of Laravel 8 since version 8.0.2 of
laravel/laravel
you can uncomment the
protected $namespace
member variable in the
RouteServiceProvider
to go back to the old way, as the route groups are setup to use this member variable for the namespace for the groups.
// protected $namespace = 'App\\Http\\Controllers';
The
only
reason uncommenting that would add the namespace prefix to the Controllers assigned to the routes is because the route groups are setup to use this variable as the namespace:
...
->namespace($this->namespace)
...
|
[
"php",
"laravel",
"laravel-8",
"laravel-routing",
"php",
"laravel",
"laravel-8",
"laravel-routing"
] |
https://stackoverflow.com/questions/63807930/error-target-class-controller-does-not-exist-when-using-laravel-8
|
Laravel Q&A
|
Proper Repository Pattern Design in PHP?
|
Preface: I'm attempting to use the repository pattern in an MVC architecture with relational databases.
I've recently started learning TDD in PHP, and I'm realizing that my database is coupled much too closely with the rest of my application. I've read about repositories and using an
IoC container
to "inject" it into my controllers. Very cool stuff. But now have some practical questions about repository design. Consider the follow example.
<?php
class DbUserRepository implements UserRepositoryInterface
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function findAll()
{
}
public function findById($id)
{
}
public function findByName($name)
{
}
public function create($user)
{
}
public function remove($user)
{
}
public function update($user)
{
}
}
Issue #1: Too many fields
All of these find methods use a select all fields (
SELECT *
) approach. However, in my apps, I'm always trying to limit the number of fields I get, as this often adds overhead and slows things down. For those using this pattern, how do you deal with this?
Issue #2: Too many methods
While this class looks nice right now, I know that in a real-world app I need a lot more methods. For example:
findAllByNameAndStatus
findAllInCountry
findAllWithEmailAddressSet
findAllByAgeAndGender
findAllByAgeAndGenderOrderByAge
Etc.
As you can see, there could be a very, very long list of possible methods. And then if you add in the field selection issue above, the problem worsens. In the past I'd normally just put all this logic right in my controller:
<?php
class MyController
{
public function users()
{
$users = User::select('name, email, status')
->byCountry('Canada')->orderBy('name')->rows();
return View::make('users', array('users' => $users));
}
}
With my repository approach, I don't want to end up with this:
<?php
class MyController
{
public function users()
{
$users = $this->repo->get_first_name_last_name_email_username_status_by_country_order_by_name('Canada');
return View::make('users', array('users' => $users))
}
}
Issue #3: Impossible to match an interface
I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like
findAllInCountry()
. Now I need to update my interface to also have this method, otherwise, other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.
Specification Pattern?
This leads me to believe that repository should only have a fixed number of methods (like
save()
,
remove()
,
find()
,
findAll()
, etc). But then how do I run specific lookups? I've heard of the
Specification Pattern
, but it seems to me that this only reduces an entire set of records (via
IsSatisfiedBy()
), which clearly has major performance issues if you're pulling from a database.
Help?
Clearly, I need to rethink things a little when working with repositories. Can anyone enlighten on how this is best handled?
|
I thought I'd take a crack at answering my own question. What follows is just one way of solving the issues 1-3 in my original question.
Disclaimer: I may not always use the right terms when describing patterns or techniques. Sorry for that.
The Goals:
Create a complete example of a basic controller for viewing and editing
Users
.
All code must be fully testable and mockable.
The controller should have no idea where the data is stored (meaning it can be changed).
Example to show a SQL implementation (most common).
For maximum performance, controllers should only receive the data they need—no extra fields.
Implementation should leverage some type of data mapper for ease of development.
Implementation should have the ability to perform complex data lookups.
The Solution
I'm splitting my persistent storage (database) interaction into two categories:
R
(Read) and
CUD
(Create, Update, Delete). My experience has been that reads are really what causes an application to slow down. And while data manipulation (CUD) is actually slower, it happens much less frequently, and is therefore much less of a concern.
CUD
(Create, Update, Delete) is easy. This will involve working with actual
models
, which are then passed to my
Repositories
for persistence. Note, my repositories will still provide a Read method, but simply for object creation, not display. More on that later.
R
(Read) is not so easy. No models here, just
value objects
. Use arrays
if you prefer
. These objects may represent a single model or a blend of many models, anything really. These are not very interesting on their own, but how they are generated is. I'm using what I'm calling
Query Objects
.
The Code:
User Model
Let's start simple with our basic user model. Note that there is no ORM extending or database stuff at all. Just pure model glory. Add your getters, setters, validation, whatever.
class User
{
public $id;
public $first_name;
public $last_name;
public $gender;
public $email;
public $password;
}
Repository Interface
Before I create my user repository, I want to create my repository interface. This will define the "contract" that repositories must follow in order to be used by my controller. Remember, my controller will not know where the data is actually stored.
Note that my repositories will only every contain these three methods. The
save()
method is responsible for both creating and updating users, simply depending on whether or not the user object has an id set.
interface UserRepositoryInterface
{
public function find($id);
public function save(User $user);
public function remove(User $user);
}
SQL Repository Implementation
Now to create my implementation of the interface. As mentioned, my example was going to be with an SQL database. Note the use of a
data mapper
to prevent having to write repetitive SQL queries.
class SQLUserRepository implements UserRepositoryInterface
{
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function find($id)
{
// Find a record with the id = $id
// from the 'users' table
// and return it as a User object
return $this->db->find($id, 'users', 'User');
}
public function save(User $user)
{
// Insert or update the $user
// in the 'users' table
$this->db->save($user, 'users');
}
public function remove(User $user)
{
// Remove the $user
// from the 'users' table
$this->db->remove($user, 'users');
}
}
Query Object Interface
Now with
CUD
(Create, Update, Delete) taken care of by our repository, we can focus on the
R
(Read). Query objects are simply an encapsulation of some type of data lookup logic. They are
not
query builders. By abstracting it like our repository we can change it's implementation and test it easier. An example of a Query Object might be an
AllUsersQuery
or
AllActiveUsersQuery
, or even
MostCommonUserFirstNames
.
You may be thinking "can't I just create methods in my repositories for those queries?" Yes, but here is why I'm not doing this:
My repositories are meant for working with model objects. In a real world app, why would I ever need to get the
password
field if I'm looking to list all my users?
Repositories are often model specific, yet queries often involve more than one model. So what repository do you put your method in?
This keeps my repositories very simple—not an bloated class of methods.
All queries are now organized into their own classes.
Really, at this point, repositories exist simply to abstract my database layer.
For my example I'll create a query object to lookup "AllUsers". Here is the interface:
interface AllUsersQueryInterface
{
public function fetch($fields);
}
Query Object Implementation
This is where we can use a data mapper again to help speed up development. Notice that I am allowing one tweak to the returned dataset—the fields. This is about as far as I want to go with manipulating the performed query. Remember, my query objects are not query builders. They simply perform a specific query. However, since I know that I'll probably be using this one a lot, in a number of different situations, I'm giving myself the ability to specify the fields. I never want to return fields I don't need!
class AllUsersQuery implements AllUsersQueryInterface
{
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function fetch($fields)
{
return $this->db->select($fields)->from('users')->orderBy('last_name, first_name')->rows();
}
}
Before moving on to the controller, I want to show another example to illustrate how powerful this is. Maybe I have a reporting engine and need to create a report for
AllOverdueAccounts
. This could be tricky with my data mapper, and I may want to write some actual
SQL
in this situation. No problem, here is what this query object could look like:
class AllOverdueAccountsQuery implements AllOverdueAccountsQueryInterface
{
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function fetch()
{
return $this->db->query($this->sql())->rows();
}
public function sql()
{
return "SELECT...";
}
}
This nicely keeps all my logic for this report in one class, and it's easy to test. I can mock it to my hearts content, or even use a different implementation entirely.
The Controller
Now the fun part—bringing all the pieces together. Note that I am using dependency injection. Typically dependencies are injected into the constructor, but I actually prefer to inject them right into my controller methods (routes). This minimizes the controller's object graph, and I actually find it more legible. Note, if you don't like this approach, just use the traditional constructor method.
class UsersController
{
public function index(AllUsersQueryInterface $query)
{
// Fetch user data
$users = $query->fetch(['first_name', 'last_name', 'email']);
// Return view
return Response::view('all_users.php', ['users' => $users]);
}
public function add()
{
return Response::view('add_user.php');
}
public function insert(UserRepositoryInterface $repository)
{
// Create new user model
$user = new User;
$user->first_name = $_POST['first_name'];
$user->last_name = $_POST['last_name'];
$user->gender = $_POST['gender'];
$user->email = $_POST['email'];
// Save the new user
$repository->save($user);
// Return the id
return Response::json(['id' => $user->id]);
}
public function view(SpecificUserQueryInterface $query, $id)
{
// Load user data
if (!$user = $query->fetch($id, ['first_name', 'last_name', 'gender', 'email'])) {
return Response::notFound();
}
// Return view
return Response::view('view_user.php', ['user' => $user]);
}
public function edit(SpecificUserQueryInterface $query, $id)
{
// Load user data
if (!$user = $query->fetch($id, ['first_name', 'last_name', 'gender', 'email'])) {
return Response::notFound();
}
// Return view
return Response::view('edit_user.php', ['user' => $user]);
}
public function update(UserRepositoryInterface $repository)
{
// Load user model
if (!$user = $repository->find($id)) {
return Response::notFound();
}
// Update the user
$user->first_name = $_POST['first_name'];
$user->last_name = $_POST['last_name'];
$user->gender = $_POST['gender'];
$user->email = $_POST['email'];
// Save the user
$repository->save($user);
// Return success
return true;
}
public function delete(UserRepositoryInterface $repository)
{
// Load user model
if (!$user = $repository->find($id)) {
return Response::notFound();
}
// Delete the user
$repository->delete($user);
// Return success
return true;
}
}
Final Thoughts:
The important things to note here are that when I'm modifying (creating, updating or deleting) entities, I'm working with real model objects, and performing the persistance through my repositories.
However, when I'm displaying (selecting data and sending it to the views) I'm not working with model objects, but rather plain old value objects. I only select the fields I need, and it's designed so I can maximum my data lookup performance.
My repositories stay very clean, and instead this "mess" is organized into my model queries.
I use a data mapper to help with development, as it's just ridiculous to write repetitive SQL for common tasks. However, you absolutely can write SQL where needed (complicated queries, reporting, etc.). And when you do, it's nicely tucked away into a properly named class.
I'd love to hear your take on my approach!
July 2015 Update:
I've been asked in the comments where I ended up with all this. Well, not that far off actually. Truthfully, I still don't really like repositories. I find them overkill for basic lookups (especially if you're already using an ORM), and messy when working with more complicated queries.
I generally work with an ActiveRecord style ORM, so most often I'll just reference those models directly throughout my application. However, in situations where I have more complex queries, I'll use query objects to make these more reusable. I should also note that I always inject my models into my methods, making them easier to mock in my tests.
|
[
"php",
"database",
"laravel",
"repository",
"repository-pattern",
"php",
"database",
"laravel",
"repository",
"repository-pattern"
] |
https://stackoverflow.com/questions/16176990/proper-repository-pattern-design-in-php
|
Laravel Q&A
|
PHP7 : install ext-dom issue
|
I'm running laravel 5.4 on Ubuntu 16.04 server with PHP7. trying to install
cviebrock/eloquent-sluggable
package throw some error:
pish@let:/home/sherk/ftp/www$ sudo composer require cviebrock/eloquent-sluggable
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Using version ^4.2 for cviebrock/eloquent-sluggable
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- Installation request for phpunit/php-code-coverage (installed at 4.0.7) -> satisfiable by phpunit/php-code-coverage[4.0.7].
To enable extensions, verify that they are enabled in those .ini files:
- /etc/php/7.0/cli/php.ini
- /etc/php/7.0/cli/conf.d/10-mysqlnd.ini
- /etc/php/7.0/cli/conf.d/10-opcache.ini
- /etc/php/7.0/cli/conf.d/10-pdo.ini
- /etc/php/7.0/cli/conf.d/20-calendar.ini
- /etc/php/7.0/cli/conf.d/20-ctype.ini
- /etc/php/7.0/cli/conf.d/20-exif.ini
- /etc/php/7.0/cli/conf.d/20-fileinfo.ini
- /etc/php/7.0/cli/conf.d/20-ftp.ini
- /etc/php/7.0/cli/conf.d/20-gd.ini
- /etc/php/7.0/cli/conf.d/20-gettext.ini
- /etc/php/7.0/cli/conf.d/20-iconv.ini
- /etc/php/7.0/cli/conf.d/20-json.ini
- /etc/php/7.0/cli/conf.d/20-mbstring.ini
- /etc/php/7.0/cli/conf.d/20-mcrypt.ini
- /etc/php/7.0/cli/conf.d/20-mysqli.ini
- /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini
- /etc/php/7.0/cli/conf.d/20-phar.ini
- /etc/php/7.0/cli/conf.d/20-posix.ini
- /etc/php/7.0/cli/conf.d/20-readline.ini
- /etc/php/7.0/cli/conf.d/20-shmop.ini
- /etc/php/7.0/cli/conf.d/20-sockets.ini
- /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
- /etc/php/7.0/cli/conf.d/20-sysvsem.ini
- /etc/php/7.0/cli/conf.d/20-sysvshm.ini
- /etc/php/7.0/cli/conf.d/20-tokenizer.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
Installation failed, reverting ./composer.json to its original content.
I have no problem installing this package on local version of the app .
|
First of all, read the warning! It says do
not
run composer as
root
!
Secondly, you're probably using Xampp on your local which has the required PHP libraries as default.
But in your server you're missing
ext-dom
.
php-xml
has all the related packages you need. So, you can simply install it by running:
sudo apt-get update
sudo apt install php-xml
Most likely you are missing
mbstring
too. If you get the error, install this package as well with:
sudo apt-get install php-mbstring
Then run:
composer update
composer require cviebrock/eloquent-sluggable
|
[
"php",
"laravel",
"laravel-5",
"composer-php",
"php",
"laravel",
"laravel-5",
"composer-php"
] |
https://stackoverflow.com/questions/43408604/php7-install-ext-dom-issue
|
Laravel Q&A
|
Laravel Migration Change to Make a Column Nullable
|
I created a migration with unsigned
user_id
. How can I edit
user_id
in a new migration to also make it
nullable()
?
Schema::create('throttle', function(Blueprint $table)
{
$table->increments('id');
// this needs to also be nullable, how should the next migration be?
$table->integer('user_id')->unsigned();
}
|
Laravel 5 now supports changing a column; here's an example from the offical documentation:
Schema::table('users', function($table)
{
$table->string('name', 50)->nullable()->change();
});
Source:
http://laravel.com/docs/5.0/schema#changing-columns
Laravel 4 does not support modifying columns, so you'll need use another technique such as writing a raw SQL command. For example:
// getting Laravel App Instance
$app = app();
// getting laravel main version
$laravelVer = explode('.',$app::VERSION);
switch ($laravelVer[0]) {
// Laravel 4
case('4'):
DB::statement('ALTER TABLE `pro_categories_langs` MODIFY `name` VARCHAR(100) NULL;');
break;
// Laravel 5, or Laravel 6
default:
Schema::table('pro_categories_langs', function(Blueprint $t) {
$t->string('name', 100)->nullable()->change();
});
}
|
[
"laravel",
"laravel-5",
"eloquent",
"nullable",
"laravel-migrations",
"laravel",
"laravel-5",
"eloquent",
"nullable",
"laravel-migrations"
] |
https://stackoverflow.com/questions/24419999/laravel-migration-change-to-make-a-column-nullable
|
Laravel Q&A
|
README.md exists but content is empty.
- Downloads last month
- 65