brijmansuriya commited on
Commit
e60d130
·
verified ·
1 Parent(s): a772e11

Upload data/laravel_stackoverflow_scraped.jsonl with huggingface_hub

Browse files
data/laravel_stackoverflow_scraped.jsonl ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"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"}
2
+ {"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"}
3
+ {"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<p>Foo Formated text: {{ fooFormatText($text) }}</p>\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:\n<?php\n \nif (!function_exists('testHelperFunction')) {\n function testHelperFunction()\n {\n return \"Hello, World!\";\n }\n}", "tags": ["php", "laravel", "laravel-8", "laravel-blade", "laravel-helper", "php", "laravel", "laravel-8", "laravel-blade", "laravel-helper"], "source_url": "https://stackoverflow.com/questions/28290332/how-to-create-custom-helper-functions-in-laravel", "category": "Laravel Q&A"}
4
+ {"instruction": "How to Create Multiple Where Clause Query Using Laravel Eloquent?", "input": "I'm using the Laravel Eloquent query builder and I have a query where I want a\nWHERE\nclause on multiple conditions. It works, but it's not elegant.\nExample:\n$results = User::where('this', '=', 1)\n ->where('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"}
5
+ {"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"}
6
+ {"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...\n<?php\n\npublic function up()\n{\n Schema::create('users', function ($table) {\n $table->integer(\"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"}
7
+ {"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"}
8
+ {"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"}
9
+ {"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"}
10
+ {"instruction": "Displaying HTML with Blade shows the HTML code", "input": "I have a string returned to one of my views, like this:\n$text = '<p><strong>Lorem</strong> ipsum dolor <img src=\"images/test.jpg\"></p>'\nI'm trying to display it with Blade:\n{{$text}}\nHowever, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel?\nPS. PHP\necho()\ndisplays the HTML correctly.", "output": "You need to use\n{!! $text !!}\nThe string will auto escape when using\n{{ $text }}\n.", "tags": ["php", "html", "laravel", "laravel-blade", "php", "html", "laravel", "laravel-blade"], "source_url": "https://stackoverflow.com/questions/29253979/displaying-html-with-blade-shows-the-html-code", "category": "Laravel Q&A"}
11
+ {"instruction": "How to set up file permissions for Laravel?", "input": "I'm using Apache Web Server that has the owner set to\n_www:_www\n. I never know what is the best practice with file permissions, for example when I create new Laravel 5 project.\nLaravel 5 requires\n/storage\nfolder to be writable. I found plenty of different approaches to make it work and I usually end with making it\n777\nchmod recursively. I know it's not the best idea though.\nThe official doc says:\nLaravel may require some permissions to be configured: folders within\nstorage\nand\nvendor\nrequire write access by the web server.\nDoes it mean that the web server needs access to the\nstorage\nand\nvendor\nfolders themselves too or just their current contents?\nI assume that what is much better, is changing the\nowner\ninstead of permissions. I changed all Laravel's files permissions recursively to\n_www:_www\nand that made the site work correctly, as if I changed chmod to\n777\n. 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.\nWhat is the correct approach to solve these problems?\nChange\nchmod\nChange the owner of the files to match those of the\n web server and perhaps set the text editor (and Finder?) to skip\n asking for password, or make them use\nsudo\nChange the owner of the web server to match the os user (I don't\nknow the consequences)\nSomething else", "output": "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...\nIF YOU ARE SETTING YOUR FOLDER PERMISSIONS TO 777 YOU HAVE OPENED YOUR\nSERVER TO ANYONE THAT CAN FIND THAT DIRECTORY. Clear enough??? :)\nThere 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.\nWebserver as owner (the way most people do it, and the Laravel doc's way):\nassuming www-data (it could be something else) is your webserver user.\nsudo chown -R www-data:www-data /path/to/your/laravel/root/directory\nif 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:\nsudo usermod -a -G www-data ubuntu\nOf 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).\nThen you set all your directories to 755 and your files to 644...\nSET file permissions\nsudo find /path/to/your/laravel/root/directory -type f -exec chmod 644 {} \\;\nSET directory permissions\nsudo find /path/to/your/laravel/root/directory -type d -exec chmod 755 {} \\;\nYour user as owner\nI prefer to own all the directories and files (it makes working with everything much easier), so, go to your laravel root directory:\ncd /var/www/html/laravel >> assuming this is your current root directory\nsudo chown -R $USER:www-data .\nThen I give both myself and the webserver permissions:\nsudo find . -type f -exec chmod 664 {} \\; \nsudo find . -type d -exec chmod 775 {} \\;\nThen give the webserver the rights to read and write to storage and cache\nWhichever 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 :\nsudo chgrp -R www-data storage bootstrap/cache\nsudo chmod -R ug+rwx storage bootstrap/cache\nNow, you're secure and your website works, AND you can work with the files fairly easily", "tags": ["php", "apache", "laravel", "laravel-5", "file-permissions", "php", "apache", "laravel", "laravel-5", "file-permissions"], "source_url": "https://stackoverflow.com/questions/30639174/how-to-set-up-file-permissions-for-laravel", "category": "Laravel Q&A"}
12
+ {"instruction": "Laravel Eloquent Query: Using WHERE with OR AND OR?", "input": "How do I say\nWHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)\nFor more complicated queries am I supposed to use raw SQL?", "output": "Make use of\nLogical Grouping\n(Laravel\n7.x\n/\n4.2\n). For your example, it'd be something like this:\nModel::where(function ($query) {\n $query->where('a', '=', 1)\n ->orWhere('b', '=', 1);\n})->where(function ($query) {\n $query->where('c', '=', 1)\n ->orWhere('d', '=', 1);\n});", "tags": ["php", "laravel", "eloquent", "laravel-query-builder", "php", "laravel", "eloquent", "laravel-query-builder"], "source_url": "https://stackoverflow.com/questions/16995102/laravel-eloquent-query-using-where-with-or-and-or", "category": "Laravel Q&A"}
13
+ {"instruction": "Get the Last Inserted Id Using Laravel Eloquent", "input": "I'm currently using the below code to insert data in a table:\n<?php\n\npublic function saveDetailsCompany()\n{\n $post = Input::All();\n\n $data = new Company;\n $data->nombre = $post['name'];\n $data->direccion = $post['address'];\n $data->telefono = $post['phone'];\n $data->email = $post['email'];\n $data->giro = $post['type'];\n $data->fecha_registro = date(\"Y-m-d H:i:s\");\n $data->fecha_modificacion = date(\"Y-m-d H:i:s\");\n\n if ($data->save()) {\n return Response::json(array('success' => true), 200);\n }\n}\nI want to return the last ID inserted but I don't know how to get it.\nKind regards!", "output": "After\nsave\n,\n$data->id\nshould be the last id inserted.\n$data->save();\n$data->id;\nCan be used like this.\nreturn Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);\nFor updated laravel version try this\nreturn response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);", "tags": ["php", "database", "laravel", "eloquent", "php", "database", "laravel", "eloquent"], "source_url": "https://stackoverflow.com/questions/21084833/get-the-last-inserted-id-using-laravel-eloquent", "category": "Laravel Q&A"}
14
+ {"instruction": "Laravel Checking If a Record Exists", "input": "I am new to Laravel. How do I find if a record exists?\n$user = User::where('email', '=', Input::get('email'));\nWhat can I do here to see if\n$user\nhas a record?", "output": "It depends if you want to work with the user afterwards or only check if one exists.\nIf you want to use the user object if it exists:\n$user = User::where('email', '=', Input::get('email'))->first();\nif ($user === null) {\n // user doesn't exist\n}\nAnd if you only want to check\nif (User::where('email', '=', Input::get('email'))->count() > 0) {\n // user found\n}\nOr even nicer\nif (User::where('email', '=', Input::get('email'))->exists()) {\n // user found\n}", "tags": ["php", "laravel", "laravel-5", "eloquent", "conditional-statements", "php", "laravel", "laravel-5", "eloquent", "conditional-statements"], "source_url": "https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists", "category": "Laravel Q&A"}
15
+ {"instruction": "Laravel - Eloquent \"Has\", \"With\", \"WhereHas\" - What do they mean?", "input": "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\nhas\nand\nwith\nis, in the context of an example (if possible)?", "output": "With\nwith()\nis for\neager loading\n. 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.\nExample:\nUser > hasMany > Post\n$users = User::with('posts')->get();\nforeach($users as $user){\n $users->posts; // posts is already loaded and no additional DB query is run\n}\nHas\nhas()\nis to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use\nhas('relation')\nthat means you only want to get the models that have at least one related model in this relation.\nExample:\nUser > hasMany > Post\n$users = User::has('posts')->get();\n// only users that have at least one post are contained in the collection\nWhereHas\nwhereHas()\nworks basically the same as\nhas()\nbut allows you to specify additional filters for the related model to check.\nExample:\nUser > hasMany > Post\n$users = User::whereHas('posts', function($q){\n $q->where('created_at', '>=', '2015-01-01 00:00:00');\n})->get();\n// only users that have posts from 2015 on forward are returned", "tags": ["laravel", "orm", "eloquent", "relational-database", "relationship"], "source_url": "https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean", "category": "Laravel Q&A"}
16
+ {"instruction": "Could not open input file: artisan", "input": "When trying to create a new laravel project, The following error appears on the CLI:\nCould not open input file: artisan\nScript php artisan clear-compiled handling the post-install-cmd event returned with an error\nI 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", "output": "You need to first\ncreate Laravel project\nand if you already have one you need to go to this project dir using\ncd\ncommand in terminal for example\ncd myproject\n.\nNow you will be able to run any artisan commands, for example running\nphp artisan\nwill display you list of available commands.", "tags": ["php", "laravel", "laravel-4", "laravel-artisan", "php", "laravel", "laravel-4", "laravel-artisan"], "source_url": "https://stackoverflow.com/questions/26193314/could-not-open-input-file-artisan", "category": "Laravel Q&A"}
17
+ {"instruction": "How to query all the GraphQL type fields without writing a long query?", "input": "Assume you have a GraphQL type and it includes many fields.\nHow to query all the fields without writing down a long query that includes the names of all the fields?\nFor example, If I have these fields :\npublic function fields()\n {\n return [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the user'\n ],\n 'username' => [\n 'type' => Type::string(),\n 'description' => 'The email of user'\n ], \n 'count' => [\n 'type' => Type::int(),\n 'description' => 'login count for the user'\n ]\n\n ];\n }\nTo query all the fields usually the query is something like this:\nFetchUsers{users(id:\"2\"){id,username,count}}\nBut I want a way to have the same results without writing all the fields, something like this:\nFetchUsers{users(id:\"2\"){*}}\n//or\nFetchUsers{users(id:\"2\")}\nIs there a way to do this in GraphQL ??\nI'm using\nFolkloreatelier/laravel-graphql\nlibrary.", "output": "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.", "tags": ["php", "laravel", "graphql", "graphql-php", "php", "laravel", "graphql", "graphql-php"], "source_url": "https://stackoverflow.com/questions/34199982/how-to-query-all-the-graphql-type-fields-without-writing-a-long-query", "category": "Laravel Q&A"}
18
+ {"instruction": "Laravel - Eloquent or Fluent random row", "input": "How can I select a random row using Eloquent or Fluent in Laravel framework?\nI know that by using SQL, you can do order by RAND(). However, I would like to get the random row\nwithout\ndoing a count on the number of records prior to the initial query.\nAny ideas?", "output": "Laravel >= 5.2:\nUser::inRandomOrder()->get();\nor to get the specific number of records\n// 5 indicates the number of records\nUser::inRandomOrder()->limit(5)->get();\n// get one random record\nUser::inRandomOrder()->first();\nor using the\nrandom\nmethod for collections:\nUser::all()->random();\nUser::all()->random(10); // The amount of items you wish to receive\nLaravel 4.2.7 - 5.1:\nUser::orderByRaw(\"RAND()\")->get();\nLaravel 4.0 - 4.2.6:\nUser::orderBy(DB::raw('RAND()'))->get();\nLaravel 3:\nUser::order_by(DB::raw('RAND()'))->get();\nCheck\nthis article\non MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using\nRAW Queries\n.\nedit 1:\nAs mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since\nthis\nchange. I updated my answer accordingly.\nedit 2:\nLaravel 5.2 finally implements\na wrapper function\nfor this. It's called\ninRandomOrder()\n.", "tags": ["php", "laravel", "random", "eloquent", "fluent", "php", "laravel", "random", "eloquent", "fluent"], "source_url": "https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row", "category": "Laravel Q&A"}
19
+ {"instruction": "How to use multiple databases in Laravel", "input": "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\nuse source of heterogeneous\ndatabase system.\nSo my question is\ndoes Laravel provide any Facade\nto deal with such situations? Or any other framework have more suitable capabilities for problem is?", "output": "From Laravel Docs\n: You may access each connection via the connection method on the\nDB\nfacade when using multiple connections. The name passed to the connection method should correspond to one of the connections listed in your\nconfig/database.php\nconfiguration file:\n$users = DB::connection('foo')->select(...);\nDefine Connections\nUsing\n.env\n>= 5.0 (or higher)\nDB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=mysql_database\nDB_USERNAME=root\nDB_PASSWORD=secret\n\nDB_CONNECTION_PGSQL=pgsql\nDB_HOST_PGSQL=127.0.0.1\nDB_PORT_PGSQL=5432\nDB_DATABASE_PGSQL=pgsql_database\nDB_USERNAME_PGSQL=root\nDB_PASSWORD_PGSQL=secret\nUsing\nconfig/database.php\n'mysql' => [\n 'driver' => env('DB_CONNECTION'),\n 'host' => env('DB_HOST'),\n 'port' => env('DB_PORT'),\n 'database' => env('DB_DATABASE'),\n 'username' => env('DB_USERNAME'),\n 'password' => env('DB_PASSWORD'),\n],\n\n'pgsql' => [\n 'driver' => env('DB_CONNECTION_PGSQL'),\n 'host' => env('DB_HOST_PGSQL'),\n 'port' => env('DB_PORT_PGSQL'),\n 'database' => env('DB_DATABASE_PGSQL'),\n 'username' => env('DB_USERNAME_PGSQL'),\n 'password' => env('DB_PASSWORD_PGSQL'),\n],\nNote:\nIn\npgsql\n, if\nDB_username\nand\nDB_password\nare the same, then you can use\nenv('DB_USERNAME')\n, which is mentioned in\n.env\nfirst few lines.\nWithout\n.env\n<= 4.0 (or lower)\napp/config/database.php\nreturn array(\n 'default' => 'mysql',\n 'connections' => array(\n # Primary/Default database connection\n 'mysql' => array(\n 'driver' => 'mysql',\n 'host' => '127.0.0.1',\n 'database' => 'mysql_database',\n 'username' => 'root',\n 'password' => 'secret'\n 'charset' => 'utf8',\n 'collation' => 'utf8_unicode_ci',\n 'prefix' => '',\n ),\n\n # Secondary database connection\n 'pgsql' => [\n 'driver' => 'pgsql',\n 'host' => 'localhost',\n 'port' => '5432',\n 'database' => 'pgsql_database',\n 'username' => 'root',\n 'password' => 'secret',\n 'charset' => 'utf8',\n 'prefix' => '',\n 'schema' => 'public',\n ]\n ),\n);\nSchema / Migration\nRun the\nconnection()\nmethod to specify which connection to use.\nSchema::connection('pgsql')->create('some_table', function($table)\n{\n $table->increments('id'):\n});\nOr, at the top, define a connection.\nprotected $connection = 'pgsql';\nQuery Builder\n$users = DB::connection('pgsql')->select(...);\nModel\n(In Laravel >= 5.0 (or higher))\nSet the\n$connection\nvariable in your model\nclass ModelName extends Model { // extend changed\n\n protected $connection = 'pgsql';\n\n}\nEloquent\n(In Laravel <= 4.0 (or lower))\nSet the\n$connection\nvariable in your model\nclass SomeModel extends Eloquent {\n protected $connection = 'pgsql';\n}\nTransaction Mode\nDB::transaction(function () {\n DB::connection('mysql')->table('users')->update(['name' => 'John']);\n DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);\n});\nor\nDB::connection('mysql')->beginTransaction();\ntry {\n DB::connection('mysql')->table('users')->update(['name' => 'John']);\n DB::connection('pgsql')->beginTransaction();\n DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);\n DB::connection('pgsql')->commit();\n DB::connection('mysql')->commit();\n} catch (\\Exception $e) {\n DB::connection('mysql')->rollBack();\n DB::connection('pgsql')->rollBack();\n throw $e;\n}\nYou can also define the connection at runtime via the\nsetConnection\nmethod or the\non\nstatic method:\nclass SomeController extends BaseController {\n public function someMethod()\n {\n $someModel = new SomeModel;\n $someModel->setConnection('pgsql'); // non-static method\n $something = $someModel->find(1);\n $something = SomeModel::on('pgsql')->find(1); // static method\n return $something;\n }\n}\nNote:\nBe 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.\nTested versions (\nUpdated\n)\nVersion\nTested (Yes/No)\n4.2\nNo\n5\nYes (5.5)\n6\nNo\n7\nNo\n8\nYes (8.4)\n9\nYes (9.2)\nUseful Links\nLaravel 5 multiple database connections FROM\nlaracasts.com\nConnect multiple databases in Laravel FROM\ntutsnare.com\nMultiple DB Connections in Laravel FROM\nfideloper.com", "tags": ["php", "mysql", "laravel", "database", "php", "mysql", "laravel", "database"], "source_url": "https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel", "category": "Laravel Q&A"}
20
+ {"instruction": "How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?", "input": "I am using Laravel 4. I would like to access the current URL inside an\n@if\ncondition in a view using the Laravel's Blade templating engine but I don't know how to do it.\nI know that it can be done using something like\n<?php echo URL::current(); ?>\nbut It's not possible inside an\n@if\nblade statement.\nAny suggestions?", "output": "You can use:\nRequest::url()\nto obtain the current URL, here is an example:\n@if(Request::url() === 'your url here')\n // code\n@endif\nLaravel offers a method to find out, whether the URL matches a pattern or not\nif (Request::is('admin/*'))\n{\n // code\n}\nCheck the related documentation to obtain different request information:\nhttp://laravel.com/docs/requests#request-information", "tags": ["laravel", "laravel-4", "laravel-blade", "laravel", "laravel-4", "laravel-blade"], "source_url": "https://stackoverflow.com/questions/17591181/how-to-get-the-current-url-inside-if-statement-blade-in-laravel-4", "category": "Laravel Q&A"}
21
+ {"instruction": "How to fix Error: laravel.log could not be opened?", "input": "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)\nError 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\nI've read this has something to do with permissions but\nchmod -R 775 storage\ndidn't help at all.", "output": "Never set a directory to 777\n. 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.\nYou can try this:\nsudo chown -R $USER:www-data storage\nsudo chown -R $USER:www-data bootstrap/cache\nthen to set directory permission try this:\nchmod -R 775 storage\nchmod -R 775 bootstrap/cache\nUpdate:\nWebserver 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:\nps aux|grep nginx|grep -v grep\nfor apache use:\nps aux | egrep '(apache|httpd)'", "tags": ["php", "laravel", "permission-denied", "php", "laravel", "permission-denied"], "source_url": "https://stackoverflow.com/questions/23411520/how-to-fix-error-laravel-log-could-not-be-opened", "category": "Laravel Q&A"}
22
+ {"instruction": "Eloquent Collection: Counting and Detect Empty", "input": "This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from\n$result = Model::where(...)->get()\nis empty, as well as counting the number of elements.\nWe are currently using\n!$result\nto detect empty result, is that sufficient? As for\ncount($result)\n, does it actually cover all cases, including empty result?", "output": "When using\n->get()\nyou cannot simply use any of the below:\nif (empty($result)) { }\nif (!$result) { }\nif ($result) { }\nBecause if you\ndd($result);\nyou'll notice an instance of\nIlluminate\\Support\\Collection\nis always returned, even when there are no results. Essentially what you're checking is\n$a = new stdClass; if ($a) { ... }\nwhich will always return true.\nTo determine if there are any results you can do any of the following:\nif ($result->first()) { } \nif (!$result->isEmpty()) { }\nif ($result->count()) { }\nif (count($result)) { }\nYou could also use\n->first()\ninstead of\n->get()\non the query builder which will return an instance of the first found model, or\nnull\notherwise. This is useful if you need or are expecting only one result from the database.\n$result = Model::where(...)->first();\nif ($result) { ... }\nNotes / References\n->first()\nhttp://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_first\nisEmpty()\nhttp://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty\n->count()\nhttp://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count\ncount($result)\nworks because the Collection implements\nCountable\nand an internal\ncount()\nmethod:\nhttp://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count\nBonus Information\nThe 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\n->all()\n->first()\n->lists()\nand others). Those methods\nalso\nexist on the\nCollection\nobject, 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\nvar_dump(User::all())\nand experimenting to see what classes it's actually returning (with help of\nget_class(...)\n). 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.\nLaravel 5.2 Collection Class\nLaravel 5.2 Query Builder", "tags": ["laravel", "laravel-4", "eloquent", "laravel-collection", "laravel", "laravel-4", "eloquent", "laravel-collection"], "source_url": "https://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty", "category": "Laravel Q&A"}
23
+ {"instruction": "How to Set Variables in a Laravel Blade Template", "input": "I'm reading the Laravel Blade\ndocumentation\nand I can't figure out how to assign variables inside a template for use later. I can't do\n{{ $old_section = \"whatever\" }}\nbecause that will echo \"whatever\" and I don't want that.\nI understand that I can do\n<?php $old_section = \"whatever\"; ?>\n, but that's not elegant.\nIs there a better, elegant way to do that in a Blade template?", "output": "EASY WAY\nIf you want to define multiple variables, use the full form of the blade directive:\n@php\n $i = 1;\n $j = 2;\n@endphp\nIf you only want to define one variable, you can also use a single PHP statement:\n@php($i = 1)\nMORE ADVANCED: ADD A 'DEFINE' TAG\nIf you want to use custom tags and use a @define instead of @php, extend Blade like this:\n/*\n|--------------------------------------------------------------------------\n| Extend blade so we can define a variable\n| <code>\n| @define $variable = \"whatever\"\n| </code>\n|--------------------------------------------------------------------------\n*/\n\n\\Blade::extend(function($value) {\n return preg_replace('/\\@define(.+)/', '<?php ${1}; ?>', $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"}
24
+ {"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"}
25
+ {"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"}
26
+ {"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"}
27
+ {"instruction": "Error “Target class controller does not exist” when using Laravel 8", "input": "Here is my controller:\n<?php\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\Controller;\nuse Illuminate\\Http\\Request;\n\nclass RegisterController extends Controller\n{\n public function register(Request $request)\n {\n dd('aa');\n }\n}\nAs seen in the screenshot, the class exists and is in the correct place:\nMy\napi.php\nroute:\nRoute::get('register', 'Api\\RegisterController@register');\nWhen I hit my\nregister\nroute using\nPostman\n, it gave me the following error:\nTarget class [Api\\RegisterController] does not exist.\nHow can I fix it?\nThanks 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.\nRoute::get('register', 'App\\Http\\Controllers\\Api\\RegisterController@register');", "output": "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.\n\"In previous releases of Laravel, the\nRouteServiceProvider\ncontained a\n$namespace\nproperty. This property's value would automatically be prefixed onto controller route definitions and calls to the\naction\nhelper /\nURL::action\nmethod. In Laravel 8.x, this property is\nnull\nby default. This means that no automatic namespace prefixing will be done by Laravel.\"\nLaravel 8.x Docs - Release Notes\nYou 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.\nuse App\\Http\\Controllers\\UserController;\n\nRoute::get('/users', [UserController::class, 'index']);\n// or\nRoute::get('/users', 'App\\Http\\Controllers\\UserController@index');\nIf you prefer the old way:\nApp\\Providers\\RouteServiceProvider\n:\npublic function boot()\n{\n ...\n\n Route::prefix('api')\n ->middleware('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"}
28
+ {"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.\n<?php\n\nclass DbUserRepository implements UserRepositoryInterface\n{\n protected $db;\n\n public function __construct($db)\n {\n $this->db = $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:\n<?php\n\nclass MyController\n{\n public function users()\n {\n $users = User::select('name, email, status')\n ->byCountry('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:\n<?php\n\nclass MyController\n{\n public function users()\n {\n $users = $this->repo->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"}
29
+ {"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"}
30
+ {"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"}