Saturday, February 29, 2020

Laravel redis : Install and Configure Redis Server for Laravel

If you are into Laravel development, you may need to utilize the awesome features like Cache or Queue to drastically improve the performance or to defer the Process of time consuming Jobs respectively , the configuration of Laravel Cache or Laravel Queue require you to choose a driver. Among the all other available drivers options, redis is one.
Due to the flexibility of the redis, its something cool your must try, Redis gives a structured way to store data in memory.  Therefore it is faster than your traditional database that writes to disk.  There are some other programs that do this like memcache; however redis offers a few more data structures to store your data in.Redis can also be used as a messaging queue using it's pubsub functionality.  Due to these features, Redis is often used to store state temporarily.  This is common with microservice architectures, session stores and data that doesn't need long term persistence.
Prerequisites
you must have root SSH access to perform the following steps

Step 1 - Login to Cpanel Server where your Laravel Project is deployed

Connect to your server via SSH as root user.

Step 2 -  Pre Installation Requirement

Run the following commands in the order, which are some of the important pre requirement for redis installation. However nowadays most linux o/s are configured with these packages already.
#update and upgrade the linux
yum -y update
yum -y upgrade

#I like nano
yum install -y nano

#Install gcc & tcl, needed for compilation
yum install -y gcc*

Step 3 - Installing Redis

run the following commands in the order to install the redis service.
wget http://download.redis.io/releases/redis-3.0.1.tar.gz
tar xzf redis-3.0.1.tar.gz
cd redis-3.0.1
make
make test
make install
cd utils
chmod +x install_server.sh
./install_server.sh
sudo chkconfig --level 2345 redis on

Step 4 - Status check and Start,Stop,Restart redis services

use the following commands to check the current status of the redis service, whether its running or down, if you didn't choose default port no during the installation, then you have to adjust port no that matching to yours, 
service redis_6379 status
to start,stop and restart redis service, you may run the following commands, 
service redis_6379 start
service redis_6379 stop
service redis_6379 restart

Step 5 -  Set a Password

you must set a password to secure your redis service, let's go and edit the redis configuration file using nano editor, use the following command.
nano /etc/redis/6379.conf
and then find the line # requirepass foobared in the file,
un-comment the above line and replace "foobared" with your password like below
requirepass somePassword
and press CTRL+O to save the file and restart the redis service.

Step 6 -  Configure Redis for Laravel Project

Before using Redis with Laravel, you will need to install the predis/predis package via Composer:
composer require predis/predis
Configuration
The Redis configuration for your application is located in the config/database.php configuration file. Within this file, you will see a redis array containing the Redis servers utilized by your application:
'redis' => [

    'client' => 'predis',

    'default' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],
The default server configuration should suffice for development. However, you are free to modify this array based on your environment, Please note that you must set the following value in your .env file of the Laravel project with the values that match your configuration details.
  • REDIS_HOST=localhost
  • REDIS_PASSWORD = somePassword
  • REDIS_PORT = 6379

If you have any other questions, experience or insights on "Install and Configure Redis Server for Laravel Project" please feel free to leave your thoughts in the comments bellow which might be helpful to someone some day!.
For windows installation: 




Wednesday, February 26, 2020

Laravel: Loading multiple views from the same controller

$view = View::make('header_admin_template'); $view->nest('home_view', 'home_view'); $view->nest('footer_admin_template', 'footer_admin_template'); return $view;

https://laravel.io/forum/03-18-2014-loading-multiple-views-form-the-same-controller

Tuesday, February 25, 2020

Laravel category and childcategory Recursive relations

Eloquent: Recursive hasMany Relationship with Unlimited Subcategories

Quite often in e-shops you can see many level of categories and subcategories, sometimes even unlimited. This article will show you how to achieve it elegantly with Laravel Eloquent.
We will be building a mini-project to views children shop sub-categories, five level deep, like this:

Database Migration

Here’s a simple schema of DB table:
Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->unsignedBigInteger('category_id')->nullable();
    $table->foreign('category_id')->references('id')->on('categories');
    $table->timestamps();
});
We just have a name field, and then relationship to the table itself. So most parent category will have category_id = NULL, and every other sub-category will have its own parent_id.
Here’s our data in the database:

Eloquent Model and Relationships

First, in app/Category.php we add a simple hasMany() method, so category may have other subcategories:
class Category extends Model
{

    public function categories()
    {
        return $this->hasMany(Category::class);
    }

}
Now comes the biggest “trick” of the article. Did you know that you can describe recursive relationship? Like this:
public function childrenCategories()
{
    return $this->hasMany(Category::class)->with('categories');
}
So, if you call Category::with(‘categories’), it will get you one level of “children”, but Category::with(‘childrenCategories’) will give you as many levels as it could find.

Route and Controller method

Now, let’s try to show all the categories and subcategories, as in the example above.
In routes/web.php, we add this:
Route::get('categories', 'CategoryController@index');
Then, app/Http/CategoryController.php looks like this:
public function index()
{
    $categories = Category::whereNull('category_id')
        ->with('childrenCategories')
        ->get();
    return view('categories', compact('categories'));
}
As you can see, we’re loading only parent categories, with children as relationships. Simple, huh?

View and Recursive Sub-View

Finally, to the Views structure. Here’s our resources/views/categories.blade.php:
    @foreach ($categories as $category)
  • {{ $category->name }}
    • @foreach ($category->childrenCategories as $childCategory) @include('child_category', ['child_category' => $childCategory]) @endforeach
    @endforeach
As you can see, we load the main categories, and then load children categories with @include.
The best part is that resources/views/admin/child_category.blade.php will use recursive loading of itself. See the code:

  • {{ $child_category->name }}
  • @if ($child_category->categories)
      @foreach ($child_category->categories as $childCategory) @include('child_category', ['child_category' => $childCategory]) @endforeach
    @endif
    As you can see, inside of child_category.blade.php we have @include(‘child_category’), so the template is recursively loading children, as long as there are categories inside of the current child category.

    And, that’s it! We have unlimited level of subcategories – in database, in Eloquent relationships, and in Views.
    https://laraveldaily.com/eloquent-recursive-hasmany-relationship-with-unlimited-subcategories/



    Laravel spark

    Spark is a Laravel package that provides scaffolding for all of the stuff you don't want to code. Subscription billing? We got that. Invoices? No problem.
    We even take care of authentication, password reset, team billing, two-factor authentication, profile photos, and more. It's the perfect starting point for your next big idea.

    https://spark.laravel.com/

    Saturday, February 22, 2020

    Laravel: implement infinite ajax scroll pagination

    Step 1: Add Table and Model
    we require to create new table "posts" that way we will get data from this table, you can use your own table but this is for example. we have to create migration for posts table using Laravel 5 php artisan command, so first fire bellow command:
    php artisan make:migration create_post_table
    After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create posts table.
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    class CreatePostTable extends Migration
    {
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
    Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('description');
    $table->timestamps();
    });
    }
    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
    Schema::drop("posts");
    }
    }
    Ok, now we have to run migration using laravel artisan command:
    php artisan migrate
    Now, we require to create table model for posts table, so fist create new Post.php in your app directory as like bellow:
    app/Post.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Post extends Model
    {
    public $fillable = ['title','description'];
    }
    Step 2: Add Route
    In this is step we need to add route for generate view. so open your app/Http/routes.php file and add following route.
    Route::get('my-post', 'PostController@myPost');
    Step 3: Create Controller
    If you haven't PostController then we should create new controller as PostController in this path app/Http/Controllers/PostController.php. Make sure you should have posts table with some data. this controller will manage data and view file, so put bellow content in controller file:
    app/Http/Controllers/PostController.php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Post;
    class PostController extends Controller
    {
    public function myPost(Request $request)
    {
    $posts = Post::paginate(5);
    if ($request->ajax()) {
    $view = view('data',compact('posts'))->render();
    return response()->json(['html'=>$view]);
    }
    return view('my-post',compact('posts'));
    }
    }
    Step 4: Create View Files
    In last step, we have to create view two file "my-post.blade.php" for main view and another for data, so first create my-post.blade.php file:
    resources/view/my-post.php
    </span><span class="pln" style="box-sizing: border-box; color: rgb(255, 255, 255);">Laravel infinite scroll pagination</span><span class="tag" style="box-sizing: border-box; color: rgb(240, 230, 140); font-weight: bold;">
    rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    class="container">

    class="text-center">Laravel infinite scroll pagination


    class="col-md-12" id="post-data">
    @include('data')

    class="ajax-load text-center" style="display:none">
    src="http://demo.itsolutionstuff.com/plugin/loader.gif">Loading More post


    resources/view/data.php
    @foreach($posts as $post)
    {{ str_limit($post->description, 400) }}

    class="text-right">


    style="margin-top:5px;">
    @endforeach
    Ok, now you can check and test.....

    https://www.itsolutionstuff.com/post/how-to-implement-infinite-ajax-scroll-pagination-in-laravel-5example.html