How to Create a News Website - Full Guide
In this guide, we will learn how to create a professional news website using Laravel.
1. Requirements
- Domain name (e.g., yournewswebsite.com)
- Web hosting (Laravel-supported server)
- SSL certificate for security
- Laravel framework installed
- MySQL database
2. Install Laravel
Run the following command to install Laravel:
composer create-project --prefer-dist laravel/laravel newswebsite
Navigate to the project folder:
cd newswebsite
Run Laravel development server:
php artisan serve
3. Set Up Database
Edit the .env file and update database settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=newsdb
DB_USERNAME=root
DB_PASSWORD=
4. Create News Model and Migration
Run this command:
php artisan make:model News -m
Open the generated migration file and add these fields:
Schema::create('news', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('image')->nullable();
$table->timestamps();
});
Run the migration:
php artisan migrate
5. Create News Controller
Run this command:
php artisan make:controller NewsController
Open NewsController.php and add the following code:
use App\Models\News;
use Illuminate\Http\Request;
class NewsController extends Controller {
public function index() {
$news = News::latest()->get();
return view('news.index', compact('news'));
}
public function create() {
return view('news.create');
}
public function store(Request $request) {
$request->validate([
'title' => 'required',
'content' => 'required',
'image' => 'nullable|image'
]);
$news = new News;
$news->title = $request->title;
$news->content = $request->content;
if ($request->hasFile('image')) {
$imagePath = $request->file('image')->store('news_images', 'public');
$news->image = $imagePath;
}
$news->save();
return redirect()->route('news.index');
}
}
6. Define Routes
Update routes/web.php:
use App\Http\Controllers\NewsController;
Route::get('/news', [NewsController::class, 'index'])->name('news.index');
Route::get('/news/create', [NewsController::class, 'create'])->name('news.create');
Route::post('/news', [NewsController::class, 'store'])->name('news.store');
7. Deployment
Upload your Laravel project to the live server and run these commands:
composer install
php artisan migrate --seed
php artisan key:generate
php artisan storage:link
Comments (0)