{"instruction": "How do I get the query builder to output its raw SQL query as a string?", "input": "Given the following code:\nDB::table('users')->get();\nI want to get the raw SQL query string that the database query builder above will generate. In this example, it would be\nSELECT * FROM users\n.\nHow do I do this?", "output": "Use the\ntoSql()\nmethod on a\nQueryBuilder\ninstance.\nDB::table('users')->toSql()\nwould return:\nselect * from `users`\nThis 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.\nNote: This method works for query builder or Eloquent, however\ntoSql()\nis used instead of\nfirst()\nor\nget()\n. You cannot run the query and also get the SQL at the same time using this method.", "tags": ["php", "sql", "laravel", "eloquent", "laravel-query-builder", "php", "sql", "laravel", "eloquent", "laravel-query-builder"], "source_url": "https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string", "category": "Laravel Q&A"} {"instruction": "How can I remove a package from Laravel using PHP Composer?", "input": "What is the correct way to remove a package from Laravel using PHP Composer?\nSo far I've tried:\nRemove declaration from file\ncomposer.json\n(in the \"require\" section)\nRemove any\nclass aliases\nfrom file\napp.php\nRemove any references to the package from my code :-)\nRun\ncomposer update\nRun\ncomposer dump-autoload\nNone of these options are working! What am I missing?", "output": "Composer 1.x and 2.x\nRunning the following command will remove the package from vendor (or wherever you install packages),\ncomposer.json\nand\ncomposer.lock\n. Change vendor/package appropriately.\ncomposer remove vendor/package\nObviously you'll need to remove references to that package within your app.\nI'm currently running the following version of Composer:\nComposer version 1.0-dev (7b13507dd4d3b93578af7d83fbf8be0ca686f4b5) 2014-12-11 21:52:29\nDocumentation\nhttps://getcomposer.org/doc/03-cli.md#remove-rm-uninstall\nUpdates\n18/10/2024 - Updated URL to\nremove-rm-uninstall\ndocumentation\n27/12/2023 - Fixed URL to\nremove-rm\ndocumentation\n26/10/2020 - Updated answer to assert command works for v1.x and v2.x of Composer", "tags": ["php", "laravel", "composer-php", "uninstallation", "package-managers", "php", "laravel", "composer-php", "uninstallation", "package-managers"], "source_url": "https://stackoverflow.com/questions/23126562/how-can-i-remove-a-package-from-laravel-using-php-composer", "category": "Laravel Q&A"} {"instruction": "How to create custom helper functions in Laravel", "input": "I would like to create helper functions to avoid repeating code between views in Laravel. For example:\nview.blade.php\n
Foo Formated text: {{ fooFormatText($text) }}
\nThey're basically text formatting functions. How should I define globally available helper functions like\nfooFormatText()\n?", "output": "Create a\nhelpers.php\nfile in your app folder and load it up with composer:\n\"autoload\": {\n \"classmap\": [\n ...\n ],\n \"psr-4\": {\n \"App\\\\\": \"app/\"\n },\n \"files\": [\n \"app/helpers.php\" // <---- ADD THIS\n ]\n},\nAfter adding that to your\ncomposer.json\nfile, run the following command:\ncomposer dump-autoload\nIf you don't like keeping your\nhelpers.php\nfile in your\napp\ndirectory (because it's not a PSR-4 namespaced class file), you can do what the\nlaravel.com\nwebsite does: store the\nhelpers.php\nin the bootstrap directory\n. Remember to set it in your\ncomposer.json\nfile:\n\"files\": [\n \"bootstrap/helpers.php\"\n]\nExample:\nCreate\nhelpers.php\nin the app directory with name\napp/helpers.php\n:\nwhere('that', '=', 1)\n ->where('this_too', '=', 1)\n ->where('that_too', '=', 1)\n ->where('this_as_well', '=', 1)\n ->where('that_as_well', '=', 1)\n ->where('this_one_too', '=', 1)\n ->where('that_one_too', '=', 1)\n ->where('this_one_as_well', '=', 1)\n ->where('that_one_as_well', '=', 1)\n ->get();\nIs there a better way to do this, or should I stick with this method?", "output": "In\nLaravel 5.3\n(and still true as of\n7.x\n) you can use more granular wheres passed as an array:\n$query->where([\n ['column_1', '=', 'value_1'],\n ['column_2', '<>', 'value_2'],\n [COLUMN, OPERATOR, VALUE],\n ...\n])\nPersonally I haven't found use-case for this over just multiple\nwhere\ncalls, but fact is you can use it.\nSince June 2014 you can pass an array to\nwhere\nAs long as you want all the\nwheres\nuse\nand\noperator, you can group them this way:\n$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];\n\n// if you need another group of wheres as an alternative:\n$orThose = ['yet_another_field' => 'yet_another_value', ...];\nThen:\n$results = User::where($matchThese)->get();\n\n// with another group\n$results = User::where($matchThese)\n ->orWhere($orThose)\n ->get();\nThe above will result in such query:\nSELECT * FROM users\n WHERE (field = value AND another_field = another_value AND ...)\n OR (yet_another_field = yet_another_value AND ...)", "tags": ["php", "laravel", "eloquent", "laravel-query-builder", "php", "laravel", "eloquent", "laravel-query-builder"], "source_url": "https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent", "category": "Laravel Q&A"} {"instruction": "Rollback one specific migration in Laravel", "input": "I want\nto rollback only :\nRolled back: 2015_05_15_195423_alter_table_web_directories\nI run\nphp artisan migrate:rollback\n, 3 of my migration are rolling back.\nRolled back: 2015_05_15_195423_alter_table_web_directories\nRolled back: 2015_05_13_135240_create_web_directories_table\nRolled back: 2015_05_13_134411_create_contacts_table\nI delete\nboth of my\nweb_directories\nand my\ncontacts\ntable unintentionally. I never want that to happen, and if I can rollback only that specific one, this disaster will never happen.", "output": "Laravel 5.3+\nRollback one step. Natively.\nphp artisan migrate:rollback --step=1\nAnd here's the manual page:\ndocs\n.\nLaravel 5.2 and before\nNo way to do without some hassle. For details, check Martin Bean's\nanswer\n.", "tags": ["laravel", "laravel-4", "laravel-5", "database-migration", "laravel", "laravel-4", "laravel-5", "database-migration"], "source_url": "https://stackoverflow.com/questions/30287896/rollback-one-specific-migration-in-laravel", "category": "Laravel Q&A"} {"instruction": "Laravel Add a new column to existing table in a migration", "input": "I can't figure out how to add a new column to my existing database table using the Laravel framework.\nI tried to edit the migration file using...\ninteger(\"paid\");\n });\n}\nIn terminal, I execute\nphp artisan migrate:install\nand\nmigrate\n.\nHow do I add new columns?", "output": "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\nfor Laravel 5+:\nphp artisan make:migration add_paid_to_users_table --table=users\nfor Laravel 3:\nphp artisan migrate:make add_paid_to_users\nYou then need to use the\nSchema::table()\nmethod (as you're accessing an existing table, not creating a new one). And you can add a column like this:\npublic function up()\n{\n Schema::table('users', function($table) {\n $table->integer('paid');\n });\n}\nand don't forget to add the rollback option:\npublic function down()\n{\n Schema::table('users', function($table) {\n $table->dropColumn('paid');\n });\n}\nThen you can run your migrations:\nphp artisan migrate\nThis is all well covered in the documentation for both Laravel 4 / Laravel 5:\nSchema Builder\nMigrations\nAnd for Laravel 3:\nSchema Builder\nMigrations\nEdit:\nuse\n$table->integer('paid')->after('whichever_column');\nto add this field after specific column.\napplicable for MySQL only", "tags": ["php", "laravel", "laravel-migrations", "php", "laravel", "laravel-migrations"], "source_url": "https://stackoverflow.com/questions/16791613/laravel-add-a-new-column-to-existing-table-in-a-migration", "category": "Laravel Q&A"} {"instruction": "PDOException SQLSTATE[HY000] [2002] No such file or directory", "input": "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\nphp artisan migrate\nor\nphp artisan db:seed\n) I get an error message:\n[PDOException]\nSQLSTATE[HY000] [2002] No such file or directory\nAt 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.", "output": "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:\nLaravel 4:\nChange \"host\" in the\napp/config/database.php\nfile from \"localhost\" to \"127.0.0.1\"\nLaravel 5+:\nChange \"DB_HOST\" in the\n.env\nfile from \"localhost\" to \"127.0.0.1\"\nI 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\".\nNot sure why \"localhost\" doesn't work by default but I found this answer in a similar question solved in a symfony2 post.\nhttps://stackoverflow.com/a/9251924\nUpdate:\nSome 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\nhttps://stackoverflow.com/a/9715164\nThe 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.", "tags": ["php", "mysql", "laravel", "database", "pdo", "php", "mysql", "laravel", "database", "pdo"], "source_url": "https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory", "category": "Laravel Q&A"} {"instruction": "Laravel requires the Mcrypt PHP extension", "input": "I am trying to use the\nmigrate\nfunction in Laravel 4 on OSX. However, I am getting the following error:\nLaravel requires the Mcrypt PHP extension.\nAs far as I understand, it's already enabled (see the image below).\nWhat is wrong, and how can I fix it?", "output": "Do you have\nMAMP\ninstalled?\nUse\nwhich php\nin the terminal to see which version of PHP you are using.\nIf it's not the PHP version from MAMP, you should edit or add\n.bash_profile\nin the user's home directory, that is :\ncd ~\nIn\n.bash_profile\n, add following line:\nexport PATH=/Applications/MAMP/bin/php/php5.4.10/bin:$PATH\nEdited:\nFirst you should use command\ncd /Applications/MAMP/bin/php\nto check which PHP version from MAMP you are using and then replace with the PHP version above.\nThen\nrestart\nthe terminal to see which PHP you are using now.\nAnd it should be working now.", "tags": ["php", "laravel", "laravel-4", "mcrypt", "php", "laravel", "laravel-4", "mcrypt"], "source_url": "https://stackoverflow.com/questions/16830405/laravel-requires-the-mcrypt-php-extension", "category": "Laravel Q&A"} {"instruction": "No Application Encryption Key Has Been Specified", "input": "I'm trying to use the\nArtisan\ncommand like this:\nphp artisan serve\nIt displays:\nLaravel development server started:\nhttp://127.0.0.1:8000\nHowever, it won't automatically launch and when I manually enter\nhttp://127.0.0.1:8000\nit shows this error:\nRuntimeException No application encryption key has been specified.\nWhat's the cause of this problem, and how can it be fixed?\nI'm using\nLaravel framework 5.5-dev\n.", "output": "From\nEncryption - Laravel - The PHP Framework For Web Artisans\n:\nBefore using Laravel's encrypter, you must set a key option in your\nconfig/app.php configuration file. You should use the\nphp artisan key:generate\ncommand to generate this key\nI found it using this query in google.com:\n\"laravel add encrption key\"\n(Yes, it worked even with the typo!)\nNote that if the\n.env\nfile contains the key but you are still getting an application key error, then run\nphp artisan config:cache\nto clear and reset the config.", "tags": ["php", "laravel", "laravel-5", "laravel-artisan", "php", "laravel", "laravel-5", "laravel-artisan"], "source_url": "https://stackoverflow.com/questions/44839648/no-application-encryption-key-has-been-specified", "category": "Laravel Q&A"} {"instruction": "Displaying HTML with Blade shows the HTML code", "input": "I have a string returned to one of my views, like this:\n$text = 'Lorem ipsum dolor 
\n| @define $variable = \"whatever\"\n| \n|--------------------------------------------------------------------------\n*/\n\n\\Blade::extend(function($value) {\n return preg_replace('/\\@define(.+)/', '', $value);\n});\nThen do one of the following:\nQuick solution\n: If you are lazy, just put the code in the boot() function of the AppServiceProvider.php.\nNicer solution\n:\nCreate an own service provider. See\nhttps://stackoverflow.com/a/28641054/2169147\non how to extend blade in Laravel 5. It's a bit more work this way, but a good exercise on how to use Providers :)\nAfter the above changes, you can use:\n@define $i = 1\nto define a variable.", "tags": ["php", "laravel", "laravel-blade", "laravel-4", "blade", "blade", "php", "laravel", "laravel-blade"], "source_url": "https://stackoverflow.com/questions/13002626/how-to-set-variables-in-a-laravel-blade-template", "category": "Laravel Q&A"}
{"instruction": "\"Please provide a valid cache path\" error in laravel", "input": "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:\ncomposer self-update\n\ncomposer-update\n\nnpm install\n\nbower install\nI configured my routes and everything properly however now when I try to run my app in my browser I get the following errors:\nInvalidArgumentException in Compiler.php line 36: Please provide a\n valid cache path.\nErrorException in Filesystem.php line 111:\n file_put_contents(F:\\www\\example\\app\\storage\\framework/sessions/edf262ee7a2084a923bb967b938f54cb19f6b37d):\n failed to open stream: No such file or directory\nI 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.", "output": "Try the following:\ncreate these folders under\nstorage/framework:\nsessions\nviews\ncache\nNow it should work", "tags": ["laravel", "laravel-5", "laravel", "laravel-5"], "source_url": "https://stackoverflow.com/questions/38483837/please-provide-a-valid-cache-path-error-in-laravel", "category": "Laravel Q&A"}
{"instruction": "Get Specific Columns Using “With()” Function in Laravel Eloquent", "input": "I have two tables,\nUser\nand\nPost\n. One\nUser\ncan have many\nposts\nand one\npost\nbelongs to only one\nuser\n.\nIn my\nUser\nmodel I have a\nhasMany\nrelation...\npublic function post(){\n return $this->hasmany('post');\n}\nAnd in my\npost\nmodel I have a\nbelongsTo\nrelation...\npublic function user(){\n return $this->belongsTo('user');\n}\nNow I want to join these two tables using\nEloquent with()\nbut want specific columns from the second table. I know I can use the Query Builder but I don't want to.\nWhen in the\nPost\nmodel I write...\npublic function getAllPosts() {\n return Post::with('user')->get();\n}\nIt runs the following queries...\nselect * from `posts`\nselect * from `users` where `users`.`id` in (<1>, <2>)\nBut what I want is...\nselect * from `posts`\nselect id,username from `users` where `users`.`id` in (<1>, <2>)\nWhen I use...\nPost::with('user')->get(array('columns'....));\nIt only returns the column from the first table. I want specific columns using\nwith()\nfrom the second table. How can I do that?", "output": "This can be done one by passing a\nclosure\nfunction in\nwith()\nas second index of array\nPost::query()\n ->with(['user' => function ($query) {\n $query->select('id', 'username');\n }])\n ->get()\nIt will only select\nid\nand\nusername\nfrom the other table.\nRemember that the\nprimary key (id in this case) needs to be the first param\nin the\n$query->select()\nto actually retrieve the necessary results.", "tags": ["php", "laravel", "eloquent", "laravel-query-builder", "php", "laravel", "eloquent", "laravel-query-builder"], "source_url": "https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent", "category": "Laravel Q&A"}
{"instruction": "Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes", "input": "Migration error on Laravel 5.4 with\nphp artisan make:auth\n[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\nusers\nadd unique\nusers_email_unique\n(\nemail\n))\n[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes", "output": "According to the\nofficial Laravel 7.x documentation\n, you can solve this quite easily.\nUpdate your\n/app/Providers/AppServiceProvider.php\nto contain:\nuse Illuminate\\Support\\Facades\\Schema;\n\n/**\n * Bootstrap any application services.\n *\n * @return void\n */\npublic function boot()\n{\n Schema::defaultStringLength(191);\n}\nAlternatively, you may enable the\ninnodb_large_prefix\noption for your database. Refer to your database's documentation for instructions on how to properly enable this option.", "tags": ["mysql", "laravel", "pdo", "laravel-5", "laravel-5.4", "mysql", "laravel", "pdo", "laravel-5", "laravel-5.4"], "source_url": "https://stackoverflow.com/questions/42244541/laravel-migration-error-syntax-error-or-access-violation-1071-specified-key-wa", "category": "Laravel Q&A"}
{"instruction": "Error “Target class controller does not exist” when using Laravel 8", "input": "Here is my controller:\nmiddleware('api')\n ->namespace('App\\Http\\Controllers') // <---------\n ->group(base_path('routes/api.php'));\n\n ...\n}\nDo this for any route groups you want a declared namespace for.\nThe\n$namespace\nproperty:\nThough there is a mention of a\n$namespace\nproperty to be set on your\nRouteServiceProvider\nin the Release notes and commented in your\nRouteServiceProvider\nthis 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.\nThis information is now in the Upgrade Guide\nLaravel 8.x Docs - Upgrade Guide - Routing\nWith what the Upgrade Guide is showing the\nimportant\npart is that you are defining a namespace on your routes groups. Setting the\n$namespace\nvariable by itself\nonly\nhelps in generating URLs to actions.\nAgain, and I can't stress this enough, the\nimportant\npart is setting the namespace for the route groups, which they just happen to be doing by referencing the member variable\n$namespace\ndirectly in the example.\nUpdate:\nIf you have installed a fresh copy of Laravel 8 since version 8.0.2 of\nlaravel/laravel\nyou can uncomment the\nprotected $namespace\nmember variable in the\nRouteServiceProvider\nto go back to the old way, as the route groups are setup to use this member variable for the namespace for the groups.\n// protected $namespace = 'App\\\\Http\\\\Controllers';\nThe\nonly\nreason 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:\n...\n->namespace($this->namespace)\n...", "tags": ["php", "laravel", "laravel-8", "laravel-routing", "php", "laravel", "laravel-8", "laravel-routing"], "source_url": "https://stackoverflow.com/questions/63807930/error-target-class-controller-does-not-exist-when-using-laravel-8", "category": "Laravel Q&A"}
{"instruction": "Proper Repository Pattern Design in PHP?", "input": "Preface: I'm attempting to use the repository pattern in an MVC architecture with relational databases.\nI'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\nIoC container\nto \"inject\" it into my controllers. Very cool stuff. But now have some practical questions about repository design. Consider the follow example.\ndb = $db;\n }\n\n public function findAll()\n {\n }\n\n public function findById($id)\n {\n }\n\n public function findByName($name)\n {\n }\n\n public function create($user)\n {\n }\n\n public function remove($user)\n {\n }\n\n public function update($user)\n {\n }\n}\nIssue #1: Too many fields\nAll of these find methods use a select all fields (\nSELECT *\n) 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?\nIssue #2: Too many methods\nWhile this class looks nice right now, I know that in a real-world app I need a lot more methods. For example:\nfindAllByNameAndStatus\nfindAllInCountry\nfindAllWithEmailAddressSet\nfindAllByAgeAndGender\nfindAllByAgeAndGenderOrderByAge\nEtc.\nAs 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:\nbyCountry('Canada')->orderBy('name')->rows();\n\n return View::make('users', array('users' => $users));\n }\n}\nWith my repository approach, I don't want to end up with this:\nrepo->get_first_name_last_name_email_username_status_by_country_order_by_name('Canada');\n\n return View::make('users', array('users' => $users))\n }\n\n}\nIssue #3: Impossible to match an interface\nI 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\nfindAllInCountry()\n. 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.\nSpecification Pattern?\nThis leads me to believe that repository should only have a fixed number of methods (like\nsave()\n,\nremove()\n,\nfind()\n,\nfindAll()\n, etc). But then how do I run specific lookups? I've heard of the\nSpecification Pattern\n, but it seems to me that this only reduces an entire set of records (via\nIsSatisfiedBy()\n), which clearly has major performance issues if you're pulling from a database.\nHelp?\nClearly, I need to rethink things a little when working with repositories. Can anyone enlighten on how this is best handled?", "output": "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.\nDisclaimer: I may not always use the right terms when describing patterns or techniques. Sorry for that.\nThe Goals:\nCreate a complete example of a basic controller for viewing and editing\nUsers\n.\nAll code must be fully testable and mockable.\nThe controller should have no idea where the data is stored (meaning it can be changed).\nExample to show a SQL implementation (most common).\nFor maximum performance, controllers should only receive the data they need—no extra fields.\nImplementation should leverage some type of data mapper for ease of development.\nImplementation should have the ability to perform complex data lookups.\nThe Solution\nI'm splitting my persistent storage (database) interaction into two categories:\nR\n(Read) and\nCUD\n(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.\nCUD\n(Create, Update, Delete) is easy. This will involve working with actual\nmodels\n, which are then passed to my\nRepositories\nfor persistence. Note, my repositories will still provide a Read method, but simply for object creation, not display. More on that later.\nR\n(Read) is not so easy. No models here, just\nvalue objects\n. Use arrays\nif you prefer\n. 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\nQuery Objects\n.\nThe Code:\nUser Model\nLet'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.\nclass User\n{\n public $id;\n public $first_name;\n public $last_name;\n public $gender;\n public $email;\n public $password;\n}\nRepository Interface\nBefore 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.\nNote that my repositories will only every contain these three methods. The\nsave()\nmethod is responsible for both creating and updating users, simply depending on whether or not the user object has an id set.\ninterface UserRepositoryInterface\n{\n public function find($id);\n public function save(User $user);\n public function remove(User $user);\n}\nSQL Repository Implementation\nNow to create my implementation of the interface. As mentioned, my example was going to be with an SQL database. Note the use of a\ndata mapper\nto prevent having to write repetitive SQL queries.\nclass SQLUserRepository implements UserRepositoryInterface\n{\n protected $db;\n\n public function __construct(Database $db)\n {\n $this->db = $db;\n }\n\n public function find($id)\n {\n // Find a record with the id = $id\n // from the 'users' table\n // and return it as a User object\n return $this->db->find($id, 'users', 'User');\n }\n\n public function save(User $user)\n {\n // Insert or update the $user\n // in the 'users' table\n $this->db->save($user, 'users');\n }\n\n public function remove(User $user)\n {\n // Remove the $user\n // from the 'users' table\n $this->db->remove($user, 'users');\n }\n}\nQuery Object Interface\nNow with\nCUD\n(Create, Update, Delete) taken care of by our repository, we can focus on the\nR\n(Read). Query objects are simply an encapsulation of some type of data lookup logic. They are\nnot\nquery 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\nAllUsersQuery\nor\nAllActiveUsersQuery\n, or even\nMostCommonUserFirstNames\n.\nYou 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:\nMy repositories are meant for working with model objects. In a real world app, why would I ever need to get the\npassword\nfield if I'm looking to list all my users?\nRepositories are often model specific, yet queries often involve more than one model. So what repository do you put your method in?\nThis keeps my repositories very simple—not an bloated class of methods.\nAll queries are now organized into their own classes.\nReally, at this point, repositories exist simply to abstract my database layer.\nFor my example I'll create a query object to lookup \"AllUsers\". Here is the interface:\ninterface AllUsersQueryInterface\n{\n public function fetch($fields);\n}\nQuery Object Implementation\nThis 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!\nclass AllUsersQuery implements AllUsersQueryInterface\n{\n protected $db;\n\n public function __construct(Database $db)\n {\n $this->db = $db;\n }\n\n public function fetch($fields)\n {\n return $this->db->select($fields)->from('users')->orderBy('last_name, first_name')->rows();\n }\n}\nBefore 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\nAllOverdueAccounts\n. This could be tricky with my data mapper, and I may want to write some actual\nSQL\nin this situation. No problem, here is what this query object could look like:\nclass AllOverdueAccountsQuery implements AllOverdueAccountsQueryInterface\n{\n protected $db;\n\n public function __construct(Database $db)\n {\n $this->db = $db;\n }\n\n public function fetch()\n {\n return $this->db->query($this->sql())->rows();\n }\n\n public function sql()\n {\n return \"SELECT...\";\n }\n}\nThis 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.\nThe Controller\nNow 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.\nclass UsersController\n{\n public function index(AllUsersQueryInterface $query)\n {\n // Fetch user data\n $users = $query->fetch(['first_name', 'last_name', 'email']);\n\n // Return view\n return Response::view('all_users.php', ['users' => $users]);\n }\n\n public function add()\n {\n return Response::view('add_user.php');\n }\n\n public function insert(UserRepositoryInterface $repository)\n {\n // Create new user model\n $user = new User;\n $user->first_name = $_POST['first_name'];\n $user->last_name = $_POST['last_name'];\n $user->gender = $_POST['gender'];\n $user->email = $_POST['email'];\n\n // Save the new user\n $repository->save($user);\n\n // Return the id\n return Response::json(['id' => $user->id]);\n }\n\n public function view(SpecificUserQueryInterface $query, $id)\n {\n // Load user data\n if (!$user = $query->fetch($id, ['first_name', 'last_name', 'gender', 'email'])) {\n return Response::notFound();\n }\n\n // Return view\n return Response::view('view_user.php', ['user' => $user]);\n }\n\n public function edit(SpecificUserQueryInterface $query, $id)\n {\n // Load user data\n if (!$user = $query->fetch($id, ['first_name', 'last_name', 'gender', 'email'])) {\n return Response::notFound();\n }\n\n // Return view\n return Response::view('edit_user.php', ['user' => $user]);\n }\n\n public function update(UserRepositoryInterface $repository)\n {\n // Load user model\n if (!$user = $repository->find($id)) {\n return Response::notFound();\n }\n\n // Update the user\n $user->first_name = $_POST['first_name'];\n $user->last_name = $_POST['last_name'];\n $user->gender = $_POST['gender'];\n $user->email = $_POST['email'];\n\n // Save the user\n $repository->save($user);\n\n // Return success\n return true;\n }\n\n public function delete(UserRepositoryInterface $repository)\n {\n // Load user model\n if (!$user = $repository->find($id)) {\n return Response::notFound();\n }\n\n // Delete the user\n $repository->delete($user);\n\n // Return success\n return true;\n }\n}\nFinal Thoughts:\nThe 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.\nHowever, 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.\nMy repositories stay very clean, and instead this \"mess\" is organized into my model queries.\nI 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.\nI'd love to hear your take on my approach!\nJuly 2015 Update:\nI'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.\nI 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.", "tags": ["php", "database", "laravel", "repository", "repository-pattern", "php", "database", "laravel", "repository", "repository-pattern"], "source_url": "https://stackoverflow.com/questions/16176990/proper-repository-pattern-design-in-php", "category": "Laravel Q&A"}
{"instruction": "PHP7 : install ext-dom issue", "input": "I'm running laravel 5.4 on Ubuntu 16.04 server with PHP7. trying to install\ncviebrock/eloquent-sluggable\npackage throw some error:\npish@let:/home/sherk/ftp/www$ sudo composer require cviebrock/eloquent-sluggable\nDo not run Composer as root/super user! See https://getcomposer.org/root for details\nUsing version ^4.2 for cviebrock/eloquent-sluggable\n./composer.json has been updated\nLoading composer repositories with package information\nUpdating dependencies (including require-dev)\nYour requirements could not be resolved to an installable set of packages.\n\n Problem 1\n - phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.\n - phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.\n - Installation request for phpunit/php-code-coverage (installed at 4.0.7) -> satisfiable by phpunit/php-code-coverage[4.0.7].\n\n To enable extensions, verify that they are enabled in those .ini files:\n - /etc/php/7.0/cli/php.ini\n - /etc/php/7.0/cli/conf.d/10-mysqlnd.ini\n - /etc/php/7.0/cli/conf.d/10-opcache.ini\n - /etc/php/7.0/cli/conf.d/10-pdo.ini\n - /etc/php/7.0/cli/conf.d/20-calendar.ini\n - /etc/php/7.0/cli/conf.d/20-ctype.ini\n - /etc/php/7.0/cli/conf.d/20-exif.ini\n - /etc/php/7.0/cli/conf.d/20-fileinfo.ini\n - /etc/php/7.0/cli/conf.d/20-ftp.ini\n - /etc/php/7.0/cli/conf.d/20-gd.ini\n - /etc/php/7.0/cli/conf.d/20-gettext.ini\n - /etc/php/7.0/cli/conf.d/20-iconv.ini\n - /etc/php/7.0/cli/conf.d/20-json.ini\n - /etc/php/7.0/cli/conf.d/20-mbstring.ini\n - /etc/php/7.0/cli/conf.d/20-mcrypt.ini\n - /etc/php/7.0/cli/conf.d/20-mysqli.ini\n - /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini\n - /etc/php/7.0/cli/conf.d/20-phar.ini\n - /etc/php/7.0/cli/conf.d/20-posix.ini\n - /etc/php/7.0/cli/conf.d/20-readline.ini\n - /etc/php/7.0/cli/conf.d/20-shmop.ini\n - /etc/php/7.0/cli/conf.d/20-sockets.ini\n - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini\n - /etc/php/7.0/cli/conf.d/20-sysvsem.ini\n - /etc/php/7.0/cli/conf.d/20-sysvshm.ini\n - /etc/php/7.0/cli/conf.d/20-tokenizer.ini\n You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.\n\nInstallation failed, reverting ./composer.json to its original content.\nI have no problem installing this package on local version of the app .", "output": "First of all, read the warning! It says do\nnot\nrun composer as\nroot\n!\nSecondly, you're probably using Xampp on your local which has the required PHP libraries as default.\nBut in your server you're missing\next-dom\n.\nphp-xml\nhas all the related packages you need. So, you can simply install it by running:\nsudo apt-get update\nsudo apt install php-xml\nMost likely you are missing\nmbstring\ntoo. If you get the error, install this package as well with:\nsudo apt-get install php-mbstring\nThen run:\ncomposer update\ncomposer require cviebrock/eloquent-sluggable", "tags": ["php", "laravel", "laravel-5", "composer-php", "php", "laravel", "laravel-5", "composer-php"], "source_url": "https://stackoverflow.com/questions/43408604/php7-install-ext-dom-issue", "category": "Laravel Q&A"}
{"instruction": "Laravel Migration Change to Make a Column Nullable", "input": "I created a migration with unsigned\nuser_id\n. How can I edit\nuser_id\nin a new migration to also make it\nnullable()\n?\nSchema::create('throttle', function(Blueprint $table)\n{\n $table->increments('id');\n // this needs to also be nullable, how should the next migration be?\n $table->integer('user_id')->unsigned();\n}", "output": "Laravel 5 now supports changing a column; here's an example from the offical documentation:\nSchema::table('users', function($table)\n{\n $table->string('name', 50)->nullable()->change();\n});\nSource:\nhttp://laravel.com/docs/5.0/schema#changing-columns\nLaravel 4 does not support modifying columns, so you'll need use another technique such as writing a raw SQL command. For example:\n// getting Laravel App Instance\n$app = app();\n\n// getting laravel main version\n$laravelVer = explode('.',$app::VERSION);\n\nswitch ($laravelVer[0]) {\n\n // Laravel 4\n case('4'):\n\n DB::statement('ALTER TABLE `pro_categories_langs` MODIFY `name` VARCHAR(100) NULL;');\n break;\n\n // Laravel 5, or Laravel 6\n default: \n\n Schema::table('pro_categories_langs', function(Blueprint $t) {\n $t->string('name', 100)->nullable()->change();\n }); \n\n}", "tags": ["laravel", "laravel-5", "eloquent", "nullable", "laravel-migrations", "laravel", "laravel-5", "eloquent", "nullable", "laravel-migrations"], "source_url": "https://stackoverflow.com/questions/24419999/laravel-migration-change-to-make-a-column-nullable", "category": "Laravel Q&A"}