Mélanie  Faria

Mélanie Faria

1656712800

Como Adicionar RSS Feed No Laravel 9

RSS significa Really Simple Syndication e um RSS Feed é um arquivo XML que possui uma lista de URLs atualizados do seu site. Você pode usar o feed RSS para envio automático de atualizações de notificações por e-mail.

Neste exemplo, vamos criar uma tabela de posts com título, slug e corpo. Em seguida, criaremos uma fábrica para postagens fictícias. Em seguida, geraremos um arquivo XML e listaremos todas as URLs para postagens. É um exemplo muito básico. então vamos seguir e você obterá um arquivo de mapa do site para o seu site e o enviará para a ferramenta do webmaster.

Vamos seguir os passos abaixo:

Passo 1: Instale o Laravel

Esta etapa não é necessária; no entanto, se você não criou o aplicativo laravel, pode prosseguir e executar o comando abaixo:

composer create-project laravel/laravel example-app

Etapa 2: criar pós-migração e modelo

Nesta etapa, criaremos a migração e o modelo. Então vamos executar o comando abaixo para criar a tabela de posts.

php artisan make:migration create_posts_table

Em seguida, atualização simples abaixo do código para o arquivo de migração.

database/migrations/create_posts_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Em seguida, execute a nova migração criada com o comando abaixo:

php artisan migrate

Agora, execute o comando abaixo para criar o modelo Post.

php artisan make:model Post

Em seguida, atualize o código a seguir para o modelo Post.

app/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title', 'slug', 'body'
    ];
}

Etapa 3: criar pós-fábrica

Nesta etapa, criaremos a classe Post factory e geraremos registros fictícios usando o comando tinker. então vamos executar o comando abaixo para criar o post factory.

php artisan make:factory PostFactory

Em seguida, copie o código abaixo e atualize o arquivo PostFactory.php.

database/factories/PostFactory.php

<?php
  
namespace Database\Factories;
  
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;
  
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Em seguida, basta executar o comando tinker e criar postagens fictícias.

php artisan tinker
App\Models\Post::factory()->count(30)->create();

Etapa 4: criar rota

Nesta etapa, criaremos uma rota sitemap.xml. então vamos adicioná-lo.

rotas/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\RSSFeedController;
   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
    
Route::get('feed', [RSSFeedController::class, 'index']);

Etapa 5: criar controlador

Nesta etapa, temos que criar um novo controlador como RSSFeedController com index(). vamos pegar todos os posts e passar para o arquivo blade. retornaremos a resposta como arquivo xml. então vamos atualizar siga o código:

app/Http/Controllers/RSSFeedController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class RSSFeedController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $posts = Post::latest()->get();
  
        return response()->view('rss', [
            'posts' => $posts
        ])->header('Content-Type', 'text/xml');
    }
}

Etapa 6: criar arquivo de visualização

Na última etapa, vamos criar rss.blade.php para exibir todos os posts e colocar o seguinte código:

recursos/visualizações/rss.blade.php

<?=
'<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL
?>
<rss version="2.0">
    <channel>
        <title><![CDATA[ ]]></title>
        <link><![CDATA[ https://your-website.com/feed ]]></link>
        <description><![CDATA[ Your website description ]]></description>
        <language>en</language>
        <pubDate>{{ now() }}</pubDate>
  
        @foreach($posts as $post)
            <item>
                <title><![CDATA[{{ $post->title }}]]></title>
                <link>{{ $post->slug }}</link>
                <description><![CDATA[{!! $post->body !!}]]></description>
                <category>{{ $post->category }}</category>
                <author><![CDATA[Hardk Savani]]></author>
                <guid>{{ $post->id }}</guid>
                <pubDate>{{ $post->created_at->toRssString() }}</pubDate>
            </item>
        @endforeach
    </channel>
</rss>

Execute o aplicativo Laravel:

Todas as etapas necessárias foram feitas, agora você deve digitar o comando abaixo e pressionar enter para executar o aplicativo Laravel:

php artisan serve

Agora, vá para o seu navegador da web, digite o URL fornecido e visualize a saída do aplicativo:

http://localhost:8000/feed

Espero que possa te ajudar... 

Fonte: https://www.itsolutionstuff.com/post/laravel-9-create-rss-feed-example-tutorialexample.html

#laravel 

What is GEEK

Buddha Community

Como Adicionar RSS Feed No Laravel 9
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Juned Ghanchi

1621508419

Laravel App Development Company in India, Hire Laravel Developers

Hire our expert team of Laravel app developers for flexible PHP applications across various cloud service providers.

With this easy build technology, we develop feature-rich apps that make your complex business process a lot easier. Our apps are,

  • More secure and scalable.
  • A good framework lets you manage and organize resources better.
  • And have a rich community base.

Get your business a best in classlaravel app. Hire laravel app developers in India. We have the best organizational set-up to provide you the most advanced app development services.

#laravel app development company india #hire laravel developers india #laravel app development company #hire laravel developers #laravel development agency #laravel app programmers

sophia tondon

sophia tondon

1618970788

Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Workfolio
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-laravel-development-companies-to-hire-experts/

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

sophia tondon

sophia tondon

1620977020

Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us- https://www.valuecoders.com/hire-developers/hire-laravel-developers

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india

Seamus  Quitzon

Seamus Quitzon

1595205213

How to perform migration rollback in laravel

As we know that laravel migration provides very simple way to create database table structure. We need to create migration file and write table structure then migrate that migration. Sometimes we need to rollback that migration. So here we will discuss about the migration rollback in laravel.

We can run the rollback artisan command to rollback on a particular step. We can execute the following artisan command.

php artisan migrate:rollback --step=1

Every time when we will rollback, we will get the last batch of migration.

**Note: **This rollback command will work on laravel 5.3 or above version. For the version below 5.3, there is no command available for migration rollback in laravel.

We can also use the following command to rollback and re migrate.

php artisan migrate:refresh --step=2

It will rollback and remigrate last two migration.

You can also checkout the article for executing single migration by clicking on the link below.

How to migrate single migration in laravel

#laravel #how to perform rollback migration in laravel #laravel migration rollback #migration refresh in laravel #migration rollback batch in laravel #migration rollback for one specific migration #migration rollback in laravel