I am trying to get the data from the posts
table but I get an error message:
PostsController.php <?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function show( $slug ) {
$posts = DB::table('posts')->get();
dd($posts);
}
}
.env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root
but I get this error:
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from
posts
)
Url I am trying to access:
See the shareable laravel error message:
https://flareapp.io/share/xPQr0171#F54
Update:
Error message I get after running php artisan migrate
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667▕ // If an exception occurs when attempting to run a query, we'll format the error
668▕ // message to include the bindings with SQL, which will make this exception a
669▕ // lot more helpful to the developer instead of just the database's errors.
670▕ catch (Exception $e) {
➜ 671▕ throw new QueryException(
672▕ $query, $this->prepareBindings($bindings), $e
673▕ );
674▕ }
675▕
+37 vendor frames
38 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
Raw Code
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=laravel", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Can you test that :
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function show( $slug ) {
return response()->json(
config("database.connections.mysql.database"),
200
);
}
}
It should show your database name (laravel).
If it's not, your .env
file is invalid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.