Laravel 5.6 – AppDividend https://appdividend.com Latest Code Tutorials Fri, 14 Dec 2018 16:07:53 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel 5.6 – AppDividend https://appdividend.com 32 32 Laravel Elasticsearch Tutorial Example From Scratch https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/ https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/#comments Sat, 30 Jun 2018 23:25:57 +0000 http://localhost/wordpress/?p=1222 Elasticsearch using Elasticquent in Laravel

Laravel Elasticsearch Tutorial Example From Scratch is the today’s leading topic. For this example, we use the composer package called Elasticquent. It is called Elasticsearch for Eloquent Laravel Models. Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the […]

The post Laravel Elasticsearch Tutorial Example From Scratch appeared first on AppDividend.

]]>
Elasticsearch using Elasticquent in Laravel

Laravel Elasticsearch Tutorial Example From Scratch is the today’s leading topic. For this example, we use the composer package called ElasticquentIt is called Elasticsearch for Eloquent Laravel Models. Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the model. The Elasticquent allows you take an Eloquent model and easily index and search its contents in Elasticsearch. Okay, let us start the Laravel Elasticsearch Tutorial Example.

If you want to master in Laravel then check out this course. It has everything you want to know.
PHP with Laravel for beginners – Become a Master in Laravel

Laravel Elasticsearch Tutorial Example

We begin this example by install Elasticsearch on the mac and then set up the laravel development environment.

#Step 1: Install Elasticsearch on Mac.

If you have not previously installed Elasticsearch on the mac then you need this step otherwise you can skip this step.  Type the following cmd in your terminal to install Elasticsearch via homebrew.

brew install elasticsearch

It will install it and now start the services using the following command.

brew services start elasticsearch

#Step 2: Setup Laravel and Elasticsearch env.

Install Laravel 5.6 by the following command.

laravel new elasticlaravel

Go into the project folder.

cd elasticlaravel

Open the project in your editor.

code .

Configure the database inside the .env file.

Add the following line inside the composer.json file. We are installing Elasticquent package.

"require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.6.*",
        "laravel/tinker": "^1.0",
        "elasticquent/elasticquent": "dev-master"
    },

Type the following command to install the elasticquent package.

composer update

 

Laravel Elasticsearch Tutorial Example

Once you’ve run a composer update command, you need to register Laravel service provider, in your config/app.php file.

// config/app.php

'providers' => [
    ...
    Elasticquent\ElasticquentServiceProvider::class,
],

We also provide a facade for an elasticsearch-php client (which has connected using our settings), add following to your config/app.php if you need so.

// config/app.php

'aliases' => [
    ...
    'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,
],

#Elasticsearch Configuration

Type the following Artisan command to publish the configuration file into your config directory for Laravel 5.6.

php artisan vendor:publish --provider="Elasticquent\ElasticquentServiceProvider"

Now go to the config file at app >> config >> elastiquent.php

We need to add the index name for our application. So let us change from default to articles.

<?php

// elastiquent.php

return array(

    /*
    |--------------------------------------------------------------------------
    | Custom Elasticsearch Client Configuration
    |--------------------------------------------------------------------------
    |
    | This array will be passed to the Elasticsearch client.
    | See configuration options here:
    |
    | http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html
    */

    'config' => [
        'hosts'     => ['localhost:9200'],
        'retries'   => 1,
    ],

    /*
    |--------------------------------------------------------------------------
    | Default Index Name
    |--------------------------------------------------------------------------
    |
    | This is the index name that Elasticquent will use for all
    | Elasticquent models.
    */

    'default_index' => 'articles',

);

#Step 3: Create an Article model and migration.

We will search the articles using elasticsearch. To create a model and migration using the following command.

php artisan make:model Article -m

In your <DATETIME>_create_articles_table.php file add the schema code.

// create_articles_table.php

public function up()
{
   Schema::create('articles', function (Blueprint $table) {
       $table->increments('id');
       $table->string('title');
       $table->text('body');
       $table->string('tags');
       $table->timestamps();
   });
}

Migrate the table using the following command.

php artisan migrate

#Step 4: Create the dummy data.

Create an ArticleTableSeeder using the following command.

php artisan make:seeder ArticleTableSeeder

For generating the fake data, we use Faker library. However, before that, we need to add the protected $fillable fields inside Article.php file to prevent the mass assignment exception.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program
// Article.php

class Article extends Model
{
    protected $fillable = ['title', 'body', 'tags'];
}

Now, add the following code inside ArticleTableSeeder.php file.

<?php

// ArticleTableSeeder.php

use Illuminate\Database\Seeder;
use App\Article;

class ArticleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for($i=0; $i<50; $i++) {
          Article::create([
            'title' => $faker->sentence(3),
            'body' => $faker->paragraph(6),
            'tags' => join(',', $faker->words(4))
          ]);
        }
    }
}

Add the ArticleTableSeeder class inside DatabaseSeeder.php file which is located in the same directory.

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ArticleTableSeeder::class);
    }
}

Okay, now run the seeder and create the fake data using the following command.

php artisan db:seed

 

Elasticsearch in Laravel

#Step 5: Set up Elastiquent inside Article model.

Write the following code inside Article.php file.

<?php

// Article.php

namespace App;
use Elasticquent\ElasticquentTrait;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use ElasticquentTrait;

    protected $fillable = ['title', 'body', 'tags'];

    protected $mappingProperties = array(
        'title' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
        'body' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
        'tags' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
      );
}

Here, we add our mapping configuration for ElasticSearch. The database table has three main fields. So we need to assign the type and analyzer which in our case is standard. Remember, our index name is articles. The mappingProperties array is the fields that need to be indexed with the proper type to search and get the perfect results. Each mapping has a kind and an analyzer. Type’s can be various data types including strings, numbers, and dates. For now, we will stick to the text type but be aware that different types allow you to take advantage of different things. You can find more datatype here at the original elasticsearch docs.

Okay, now we need to index the database. So inside web.php file, write the following code. Remember, I have written the following code inside web.php file but in a real-time scenario, you need to write this inside controller or any other logical part of your app except web.php file.

#Indexing Documents

To index all the entries in an Eloquent model, use addAllToIndex:

    Article::addAllToIndex();

You can also index a collection of models:

    $articles = Article::where('id', '<', 200)->get();
    $articles->addToIndex();

You can index individual entries as well:

    $articles = Article::find($id);
    $articles->addToIndex();

You can also reindex an entire model:

     Article::reindex()

Now, we index the whole model so that we can write the indexing code inside root route.

<?php

// web.php

use App\Article;

Route::get('/', function () {
    Article::createIndex($shards = null, $replicas = null);

    Article::putMapping($ignoreConflicts = true);

    Article::addAllToIndex();

    return view('welcome');
});

Here, we have created the index. The name of the index is already defined inside config >> elastiquent.php file.

Then we have put the mapping, which is defined in the Article.php model and finally adds that to the indexing.

Go to the browser and hit this URL: http://elasticlaravel.test/

You will get the welcome page, but our data is entirely indexed and we can verify that by sending the following request using cURL. We can also use the postman for that, but I am sending the request via terminal.

curl 'localhost:9200/articles/_mapping?pretty'

 

Elastic search api for laravel with example

We can do a basic search using the following command.

curl 'localhost:9200/articles/articles/_search?q=title:Sed&pretty'

Here, our search term for the title is Sed. So it will fetch the records that have Sed term. We can see the prettify results inside a terminal.

Laravel Elasticsearch query example

 

#Step 6: Search using Laravel eloquent methods.

Okay so till now, we have used cURL for the searching the data. Now, we will use Elastiquent method to search the data. So let us create another route inside the web.php file and add the following code in it.

<?php

// Article.php

use App\Article;

Route::get('/', function () {
    Article::createIndex($shards = null, $replicas = null);

    Article::putMapping($ignoreConflicts = true);

    Article::addAllToIndex();

    return view('welcome');
});

Route::get('/search', function() {

    $articles = Article::searchByQuery(['match' => ['title' => 'Sed']]);

    return $articles;
});

I have passed the ‘Sed’ hardcoded, but in a real-time application, it will be our search term which is typed inside the search box. Now, switch to this URL: http://elasticlaravel.test/search. You can see the JSON response like this.

Search using elasticsearch in Laravel

 

Of course, you might be getting different data because it is randomly generated data. So first check the database and pick the term and then pass to the search engine and it will return something like this. So we have successfully indexed the data and fetched the data from the elasticsearch engine.

In this example, we have searched for the title, you can go for body and tags as well.

$articles = Article::searchByQuery(['match' => ['body' => 'eligendi']]);
    
return $articles;

And you can do the same for the tags as well.

#Search collections

We can get the total hits to count using the following code.

$articles = Article::searchByQuery(['match' => ['title' => 'Heleium']]);
    
 return $articles->totalHits();

Access the shards array:

 $articles->shards();

Access the max score:

 $articles->maxScore();

Access the timed out boolean property:

 $articles->timedOut();

Access the took property:

  $articles->took();

Access search aggregations – See Aggregations for details:

  $articles->getAggregations();

#Chunking results from Elastiquent.

To get the results in chunks, you can use the chunk() function.

$articles = Article::searchByQuery(['match' => ['title' => 'Similique']]);
    
return $articles->chunk(2);

Finally, Laravel Elasticsearch Tutorial Example is over. Thanks for taking.

The post Laravel Elasticsearch Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/feed/ 13
How To Create Comment Nesting In Laravel From Scratch https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/ https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/#comments Wed, 20 Jun 2018 14:33:04 +0000 http://localhost/wordpress/?p=1115 How to use nesting in laravel

How To Create Comment Nesting In Laravel From Scratch is the today’s main topic. In any topic specific forum, there is always a structure, where you need to reply to someone’s comment and then somebody reply in their comment and so on. So comment nesting is very useful in any web application, which exposes public interest. […]

The post How To Create Comment Nesting In Laravel From Scratch appeared first on AppDividend.

]]>
How to use nesting in laravel

How To Create Comment Nesting In Laravel From Scratch is the today’s main topic. In any topic specific forum, there is always a structure, where you need to reply to someone’s comment and then somebody reply in their comment and so on. So comment nesting is very useful in any web application, which exposes public interest. In this tutorial, we will do it from scratch. We use Polymorphic relationship in this example.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Check out this amazing program

Create Comment Nesting In Laravel From Scratch

As always, install Laravel using the following command. I am using Laravel Valet.

Step 1: Install and configure Laravel.

laravel new comments

# or

composer create-project laravel/laravel comments --prefer-dist

Go to the project.

cd comments

Open the project in your editor.

code .

Configure the MySQL database in the .env file.

Create an auth using the following command.

php artisan make:auth

Now migrate the database using the following command.

php artisan migrate

Step 2: Create a model and migration.

Create a Post model and migration using the following command.

php artisan make:model Post -m

Define the schema in the post migration file.

// create_posts_table

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

Also, we need to create Comment model and migration, so create by using the following command.

php artisan make:model Comment -m

Okay, now we will use the Polymorphic relationship between the models. So we need to define the schema that way.

// create_comments_table

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
       $table->increments('id');
       $table->integer('user_id')->unsigned();
       $table->integer('parent_id')->unsigned();
       $table->text('body');
       $table->integer('commentable_id')->unsigned();
       $table->string('commentable_type');
       $table->timestamps();
    });
}

Now, migrate the database using the following cmd.

php artisan migrate

 

How To Create Comment Nesting In Laravel From Scratch

Step 3: Define Polymorphic Relationships.

Now, we need to define the Polymorphic relationships between the models. So write the following code inside app >> Post.php file. 

<?php

// Post.php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
    }
}

Here, we have written all the comments, whose parent_id is null. The reason is that we need to display the parent level comment and also save the parent level comment. That is why. We need to differentiate between the Comment and its replies.

Post also belongs To a User. So we can define that relationship as well.

<?php

// Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
    }
}

Define the Comment relationship with the Post. Write the following code inside Comment.php file.

<?php

// Comment.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Step 3: Define the views, controller, and routes.

Create a PostController.php file using the following command.

php artisan make:controller PostController

Next step is to define the route for the view and store the post in the database. Write the following code inside routes >> web.php file.

<?php

// web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/post/create', 'PostController@create')->name('post.create');
Route::post('/post/store', 'PostController@store')->name('post.store');

Write the following code inside PostController.php file.

<?php

// PostController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{

    public function __construct()
    {
        return $this->middleware('auth');
    }

    public function create()
    {
        return view('post');
    }

    public function store(Request $request)
    {
        // store code
    }
}

Now, first, we need to create a form for creating the post. So create a blade file inside resources >> views folder called post.blade.php. Write the following code inside a post.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Create Post</div>
                <div class="card-body">
                    <form method="post" action="{{ route('post.store') }}">
                        <div class="form-group">
                            @csrf
                            <label class="label">Post Title: </label>
                            <input type="text" name="title" class="form-control" required/>
                        </div>
                        <div class="form-group">
                            <label class="label">Post Body: </label>
                            <textarea name="body" rows="10" cols="30" class="form-control" required></textarea>
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-success" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Okay, now go to the resources >> views >> layouts >> app.blade.php file and add a link to create a post.

We need to add the link to the @else part of the navigation bar. So, if the user is successfully logged in then and then he/she can create a post otherwise, he or she could not create a post.

@else
     <li class="nav-item">
          <a class="nav-link" href="{{ route('post.create') }}">Create Post</a>
     </li>

Now, go to this link: http://comments.test/register and register a user. After logged in, you can see the Create Post in the navbar. Click that item, and you will redirect to this route: http://comments.test/post/create. You can see, our form is there with the title and body form fields.

Comment Nesting in Laravel 5.6

 

Step 4: Save and display the Post.

Okay, now we need to save the post in the database, so write the following code inside store function of PostController.php file.

<?php

// PostController.php

namespace App\Http\Controllers;
use App\Post;

use Illuminate\Http\Request;

class PostController extends Controller
{

    public function __construct()
    {
        return $this->middleware('auth');
    }

    public function create()
    {
        return view('post');
    }

    public function store(Request $request)
    {
        $post =  new Post;
        $post->title = $request->get('title');
        $post->body = $request->get('body');

        $post->save();

        return redirect('posts');

    }
}

After saving the post, we are redirecting to the posts list page. We need to define its route too. Add the following route inside a web.php file.

// web.php

Route::get('/posts', 'PostController@index')->name('posts');

Also, we need to define the index function inside PostController.php file.

// PostController.php

public function index()
{
    $posts = Post::all();

    return view('index', compact('posts'));
}

Create an index.blade.php file inside views folder. Write the following code inside an index.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <table class="table table-striped">
                <thead>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Action</th>
                </thead>
                <tbody>
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>
                        <a href="{{ route('post.show', $post->id) }}" class="btn btn-primary">Show Post</a>
                    </td>
                </tr>
                @endforeach
                </tbody>

            </table>
        </div>
    </div>
</div>
@endsection

Now, define the show route inside a web.php file. Add the following line of code inside a web.php file.

// web.php

Route::get('/post/show/{id}', 'PostController@show')->name('post.show');

Also, define the show() function inside PostController.php file.

// PostController.php

public function show($id)
{
    $post = Post::find($id);

    return view('show', compact('post'));
}

Create a show.blade.php file inside views folder and add the following code.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <p>{{ $post->title }}</p>
                    <p>
                        {{ $post->body }}
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Okay, now you can see the individual posts. Fine till now.

Next step is to display the comments on this post.

Laravel Polymorphic morphMany relationship tutorial

 

Step 5: Create a form to add a comment.

First, create a CommentController.php file using the following command.

php artisan make:controller CommentController

Now, we need to create a form inside a show.blade.php file that can add the comment in the particular post.

Write the following code inside a show.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <p><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So, we have added a form that can add the comment. Now, we need to define the route to store the comment.

// web.php

Route::post('/comment/store', 'CommentController@store')->name('comment.add');

Okay, now write the store() function and save the comment using the morphMany() relationship.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\Post;

class CommentController extends Controller
{
    public function store(Request $request)
    {
        $comment = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user());
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($comment);

        return back();
    }
}

Okay, now if all is well then, we can now add the comments. Remember, we have not till now display the comments. Just complete the save functionality, whose parent_id is null.

Laravel Nested Set Example

 

Step 6: Display the comment.

Now, as we have set up the relationship between a Comment and a Post, we can easily pluck out all the comments related to a particular post.

So, write the following code inside the show.blade.php file. I am writing the whole file to display the comments. Remember, this is the parent comments. We still need to create a reply button and then show all the replies.

<!-- show.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <p><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Display Comments</h4>
                    @foreach($post->comments as $comment)
                        <div class="display-comment">
                            <strong>{{ $comment->user->name }}</strong>
                            <p>{{ $comment->body }}</p>
                        </div>
                    @endforeach
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, add the comment, and it will show us here in the same url.

Laravel Nesting Relationships

 

Step 7: Create a Reply form and save replies.

Now, we need to create a function called replies() inside Comment.php model.

<?php

// Comment.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

Here, in the replies function, we need to add a primary key as a parent_id because we need to fetch a reply based on a parent comment’s id.

Okay, now we need to write the display of all the comments and its replies code into the partial blade file.

The reason behind is that, we need to nest the comment replies and how much nesting is required depends upon the user interaction. So we can not predict the nesting levels.

To make more and more flexible, we need to create partials and then repeat that partial to display the nested comment replies.

First, create a partials folder inside resources >> views folder and inside partials folder, create one file called _comment_replies.blade.php.

Write the following code inside the _comment_replies.blade.php file.

<!-- _comment_replies.blade.php -->

 @foreach($comments as $comment)
    <div class="display-comment">
        <strong>{{ $comment->user->name }}</strong>
        <p>{{ $comment->body }}</p>
        <a href="" id="reply"></a>
        <form method="post" action="{{ route('reply.add') }}">
            @csrf
            <div class="form-group">
                <input type="text" name="comment_body" class="form-control" />
                <input type="hidden" name="post_id" value="{{ $post_id }}" />
                <input type="hidden" name="comment_id" value="{{ $comment->id }}" />
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-warning" value="Reply" />
            </div>
        </form>
        @include('partials._comment_replies', ['comments' => $comment->replies])
    </div>
@endforeach

Here, I have displayed all the replies with the text box. So it can do further nesting.

Now, this partial is expect to parameters.

  1. comments
  2. post_id.

So, when we include this partial inside show.blade.php file, we do need to pass these both of the parameters so that we can access here.

Also, we need to define the route to save the reply.

Add the following line of code inside routes >> web.php file.

// web.php

Route::post('/reply/store', 'CommentController@replyStore')->name('reply.add');

So, our final web.php file looks like below.

<?php

// web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/post/create', 'PostController@create')->name('post.create');
Route::post('/post/store', 'PostController@store')->name('post.store');

Route::get('/posts', 'PostController@index')->name('posts');
Route::get('/post/show/{id}', 'PostController@show')->name('post.show');

Route::post('/comment/store', 'CommentController@store')->name('comment.add');
Route::post('/reply/store', 'CommentController@replyStore')->name('reply.add');


Also, define the replyStore() function inside CommentController.php file.

I am writing here the full code of the CommentController.php file.

<?php

// CommentController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\Post;

class CommentController extends Controller
{
    public function store(Request $request)
    {
        $comment = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user());
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($comment);

        return back();
    }

    public function replyStore(Request $request)
    {
        $reply = new Comment();
        $reply->body = $request->get('comment_body');
        $reply->user()->associate($request->user());
        $reply->parent_id = $request->get('comment_id');
        $post = Post::find($request->get('post_id'));

        $post->comments()->save($reply);

        return back();

    }
}

So, here almost both of the function store and replyStore function is same. We are storing parent comment and its replies in the same table. But, when we are saving a parent comment, the parent_id becomes null, and when we store any reply, then parent_id becomes its comment_id. So that is the difference.

Finally, our show.blade.php file looks like this.

<!-- show.blade.php -->

@extends('layouts.app')
<style>
    .display-comment .display-comment {
        margin-left: 40px
    }
</style>
@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <p><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Display Comments</h4>
                    @include('partials._comment_replies', ['comments' => $post->comments, 'post_id' => $post->id])
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Here, I have defined the CSS to display proper nesting.

Also, include the partials and pass the both of the parameters.

  1. Post comments.
  2. Post id

We can add the parent comment from here but can add the replies from the partials.

I have added the parent comment, and its replies and our database table looks like this.

Laravel Nested Set Database

 

Also, our final output looks like below.

Laravel 5.6 Polymorphic Nested Relationship Example

 

Finally, Create Comment Nesting In Laravel Tutorial With Example is over.

I have put the Github Code of Create Comment Nesting In Laravel so that you can check that out as well.

Github Code

Fork Me On Github

Steps To Use Code

  1. Clone the repository.
  2. Install the dependencies
  3. Configure the database.
  4. Migrate the database using this command: php artisan migrate
  5. Go to the register page and add the one user.
  6. Create the post and comment and reply on the comment.

The post How To Create Comment Nesting In Laravel From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/feed/ 37
Laravel Desktop Notification Implementation Tutorial https://appdividend.com/2018/06/09/laravel-desktop-notification-implementation-tutorial/ https://appdividend.com/2018/06/09/laravel-desktop-notification-implementation-tutorial/#comments Sat, 09 Jun 2018 15:00:56 +0000 http://localhost/wordpress/?p=1012 Laravel 5.6 Push Notification Tutorial With Example From Scratch

Hello Developers, In this example, I will describe Laravel Desktop Notification Implementation Tutorial. I am using Pusher services to implement Desktop Notifications. For Frontend, I am using Vue.js. Real-time notifications are now very common in modern web applications as we need to keep users engaged and informed of happenings on their platform. In my blog: I am […]

The post Laravel Desktop Notification Implementation Tutorial appeared first on AppDividend.

]]>
Laravel 5.6 Push Notification Tutorial With Example From Scratch

Hello Developers, In this example, I will describe Laravel Desktop Notification Implementation Tutorial. I am using Pusher services to implement Desktop Notifications. For Frontend, I am using Vue.js. Real-time notifications are now very common in modern web applications as we need to keep users engaged and informed of happenings on their platform. In my blog: I am also using Desktop Notifications, but the service I am using is One Signal. It is also Good option to implement Desktop Push Notification.

In this tutorial, I am using Laravel and  Pusher to build a real-time app, with desktop notifications, utilizing the Notification API provided by the Browsers.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

Laravel Desktop Notification Implementation

In general blog scenario, when the author post new article, all the subscribers get the notification about that latest post. We also implement the same scenario in which, we create a simple form to create a new article and then send a desktop push notification.

Step 1: Install Laravel 5.6

I am using Laravel Valet, so I am installing Laravel using the following command.

laravel new notify

If you are not using Laravel Valet software, then type the following command.

composer create-project laravel/laravel notify --prefer-dist

Go into the project.

cd notify

After that, Install the NPM dependencies using the following command.

npm install

Configure the database inside the .env file.

Step 2: Create Model, Controller and migration files.

Create a model and migration using the following command.

php artisan make:model Post -m

Write the following schema inside create_posts_table.

// create_posts_table

public function up()
{
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
}

Migrate the schema using this command.

php artisan migrate

Create a controller using the following command.

php artisan make:controller PostController

Step 3: Create a route and view file.

Inside routes >> web.php file, define the following route. It will redirect us to view the file.

// web.php

Route::get('post', 'PostController@create')->name('create');

Now, we need to store the data via an API so that we can define the store route inside routes >> api.php file.

// api.php

Route::post('post', 'PostController@store')->name('store');

Inside PostController.php file, write the following function.

// PostController.php

public function create()
{
    return view('post');
}

Now, create a blade file inside resources >> views folder called post.blade.php.

Write the following code inside a post.blade.php file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Simple Post</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet"/>
</head>
<body>
    <div id="app">
        <form-component></form-component>
    </div>
    <script>
        window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
        ]) !!};
  </script>
  <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Now, I have not written the form component yet, so I leave it here, but I will come back when we start building frontend with Vue.js.

Now, write the store function to save the post data in the database.

// PostController.php

public function store(Request $request)
{
     $post = new Post;
     $post->title = $request->get('title');
     $post->body = $request->get('body');

     $post->save();

     return response($post);
}

Step 4: Create an Event in Laravel.

Events are the great way to separate out a business logic. We can define events to be triggered in our application when an action occurs, and we can define listeners, to listen for such events.

Laravel allows for the exact definition of events and listeners out of the box. It also includes helper functions and classes to let us easily trigger and broadcast events.

Create an event using the following command.

php artisan make:event PostCreated

The PostCreated Event file is created inside App\Events folder.

Now, write the following code inside PostCreated file.

<?php

// PostCreated.php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Post;

class PostCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $post;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function broadcastWith()
    {
        return [
          'title' => $this->post->title,
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('posts');
    }
}

Step 5: Install Pusher PHP Server.

Install pusher-php-server using the following command.

composer require pusher/pusher-php-server

Installing Laravel Echo and Pusher-js which we will use to listen for broadcasted events.

npm install -S laravel-echo pusher-js

Next, we will do some configuration to let Laravel know we will be using Pusher to manage our broadcasts. So, we need to add some credentials to integrate the API.

Now add the Pusher credentials inside the .env file.

BROADCAST_DRIVER=pusher

PUSHER_APP_ID=your_pusher_add_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_APP_CLUSTER=your_cluster

Step 6: Configure Frontend.

First uncomment the following code inside resources >> assets >> js >> bootstrap.js file.

 

// bootstrap.js
import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

Rename the file inside resources >> assets >> js >> components folder called ExampleComponent.vue to FormComponent.vue file and add the following code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control"></textarea>
            </div>
            <button class="btn btn-primary">Submit</button>
        </form>
    </div>
</template>

<script>
    export default {
    }
</script>

Now, import this component inside resources >> assets >> js >> app.js file.

// app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('form-component', require('./components/FormComponent.vue'));

const app = new Vue({
    el: '#app'
});

Add the form component inside a form.blade.php file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Simple Post</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet"/>
</head>
<body>
    <div id="app">
        <form-component></form-component>
    </div>
    <script>
        window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
        ]) !!};
    </script>
  <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Save the file and go to the terminal and type the following command.

npm run watch

Go to this URL: http://notify.test/post or http://localhost:8000/post

You can see the Form like this.

Laravel Desktop Notification Implementation Tutorial Example From Scratch

 

Step 7: Send a Post Request.

Okay, now we need to add some code inside FormComponent.vue component.

I am here writing the whole file to send a post request to the Laravel Server and save the data into the database.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px" @submit.prevent="createPost">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control" v-model="title">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control" v-model="body"></textarea>
            </div>
            <button
                :class="{ disabled: (!title || !body) }"
                class="btn btn-primary">
                    Submit
            </button>
        </form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                title: "", 
                body: "" 
            }
        },
        
        methods: {
            createPost() {
                if(!this.title || !this.body)
                return;

                axios.post('/api/post', {
                    title: this.title, body: this.body
                    }).then( response => {
                    if(response.data) { 
                        this.title = this.body = "";
                    }
                })
            }
        }
    }
</script>

So, I have created two-way data binding to get the data from the form and check that data, if they are empty or not and then send the post request to the server. In the response, I have emptied all the fields.

Also, if you have not filled any fields then the submit button will be disabled and when all the fields are filled, it will enable so that you can submit the data to the server.

Save the file and try to submit the data and if everything works correctly, then you can save the data into the database.

Step 8: Listen for the event.

Now, inside FormComponent.vue file, you have to add the event listeners.

I am writing the final code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px" @submit.prevent="createPost">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control" v-model="title">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control" v-model="body"></textarea>
            </div>
            <button
                :class="{ disabled: (!title || !body) }"
                class="btn btn-primary">
                    Submit
            </button>
        </form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                title: "", 
                body: "" 
            }
        },
        created() {
            this.listenEvent();
        },
        methods: {
            createPost() {
                if(!this.title || !this.body)
                return;

                axios.post('/api/post', {
                    title: this.title, body: this.body
                    }).then( response => {
                    if(response.data) { 
                        this.title = this.body = "";
                    }
                })
            },
            listenEvent() {
                    Echo.channel('posts')
                    .listen('PostCreated', post => {
                        if (! ('Notification' in window)) {
                        alert('Web Notification is not supported');
                        return;
                        }

                        Notification.requestPermission( permission => {
                        let notification = new Notification('New post alert!', {
                            body: post.title
                        });

                        notification.onclick = () => {
                            window.open(window.location.href);
                        };
                    });
                });
            }
        }
    }
</script>

So, when the PostCreated event is triggered by Laravel, it listened by this function listenEvent.

Now, if the permission is given by the browser, then it will sure give a notification about the latest post.

Note: Firefox and Safari are right now supported to receive the push notification on HTTP origin. Google Chrome is not supported. It will give you the deprecation warning to use HTTPS version of your site. I have not checked Edge or IE.

Finally, We have implemented primary Desktop Push Notification in Laravel using Vue and Pusher service.

The Laravel Desktop Notification Implementation Tutorial is over. Thanks for taking.

The post Laravel Desktop Notification Implementation Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/09/laravel-desktop-notification-implementation-tutorial/feed/ 15
Laravel Avatar Image Upload Tutorial With Example https://appdividend.com/2018/06/02/laravel-avatar-image-upload-tutorial-with-example/ https://appdividend.com/2018/06/02/laravel-avatar-image-upload-tutorial-with-example/#comments Sat, 02 Jun 2018 05:21:09 +0000 http://localhost/appdividend/?p=2863 Laravel Avatar Image Upload Tutorial With Example

Laravel Avatar Image Upload Tutorial With Example is the topic, we will discuss today. We will use laravel 5.6 with Spatie’s Media Library Package. By default, Laravel registration form includes only the name, email, and password, but usually, it’s helpful to allow the user to upload the photo or an avatar. Earn a Tech Degree and get the skills […]

The post Laravel Avatar Image Upload Tutorial With Example appeared first on AppDividend.

]]>
Laravel Avatar Image Upload Tutorial With Example

Laravel Avatar Image Upload Tutorial With Example is the topic, we will discuss today. We will use laravel 5.6 with Spatie’s Media Library Package. By default, Laravel registration form includes only the name, email, and password, but usually, it’s helpful to allow the user to upload the photo or an avatar.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

Laravel Avatar Image Upload Tutorial With Example

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel uploadavatarimages

Step 2: Setup SQL Database

Now we can setup database credentials.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=avatarimageupload
DB_USERNAME=root
DB_PASSWORD=

Next, Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make:auth

This command should be applied to new applications and will install a layout view, registration and login views, as well as routes to all authentication end-points.

Step 3: Modify User Registration Form

Now we can add an avatar in resources  >>  views  >> auth >>  register.blade.php file.

<!-- register.blade.php -->

<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar (optional)') }}</label>

    <div class="col-md-6">
        <input id="avatar" type="file" class="form-control" name="avatar">
    </div>
</div>

Also, you can add enctype=”multipart/form-data” in form. So final code of register.blade.php looks like that

<!-- register.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Register') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
                        @csrf

                        <div class="form-group row">
                            <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>

                                @if ($errors->has('name'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>

                                @if ($errors->has('email'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                            </div>
                        </div>

                    <div class="form-group row">
                        <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar (optional)') }}</label>

                        <div class="col-md-6">
                             <input type="file" class="form-control" name="avatar" id="avatar">
                        </div>
                    </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Register') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

If you don’t have add enctype then you see an error like this:

Error : Spatie \ MediaLibrary \ Exceptions \ FileCannotBeAdded \ RequestDoesNotHaveFile The current request does not have a file in a key named `avatar`

laravel profile picture upload tutorial with example

 

Step 4: Install Spatie’s Media Library Package

First, install Spatie’s Media Library Package via the Composer package manager.

composer require spatie/laravel-medialibrary:^7.0.0

After installing Spatie’s Media Library, you should publish the Spatie’s Media Library configuration using the vendor: publish Artisan command.

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"

Finally, we have migrations in our published folder:

php artisan migrate

It will generate a database table called media which uses Polymorphic Relations to store the data. You can see an error like this:

Error : [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that correspond to your MariaDB server version of the right syntax to use ‘json not null, custom_properties json not null, order_column int unsigned nu’ at line 1 (SQL: create table m edia(id int unsigned not null auto_increment primary key, model_id int unsigned not null, model _typevarchar(191) not null, collection_name varchar(191) not null, name varchar(191) not null, file_namevarchar(191) not null, mime_type varchar(191) null, disk varchar(191) not null, size int unsigned not null, manipulations json not null, custom_properties json not null, order_column int unsigned null, created_at timestamp null, updated_at timestamp null) default character set u
tf8mb4 collate utf8mb4_unicode_ci)

Possible Solution: you can change datatype json to text in database  >>  migration  >> create_media_table.php file.

Media table looks like that

//create_media_table.php

public function up()
    {
        Schema::create('media', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('model');
            $table->string('collection_name');
            $table->string('name');
            $table->string('file_name');
            $table->string('mime_type')->nullable();
            $table->string('disk');
            $table->unsignedInteger('size');
            $table->text('manipulations');
            $table->text('custom_properties');
            $table->text('responsive_images');
            $table->unsignedInteger('order_column')->nullable();
            $table->nullableTimestamps();
        });
    }

Step 5: Change the User Model File 

Now, let’s develop that app >> User.php model to work with Media Library. Add Following code in User.php file.

//User.php

use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;

class User extends Authenticatable implements HasMedia
{
    // ...
    use HasMediaTrait;
}

Here we can add HasMediaTrait and HasMedia. Both come from Media Library.

Now, back to our RegisterController and add some code to the create()method:

//RegisterController.php

protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
        if (isset($data['avatar'])) {
            $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');
        }
        return $user;
    }

The images uploaded to storage directory to be public. Change the following.

Change disk config: Open filesystems.php which is located in the config directory. Change the default parameter from the local to the public.

'default' => env('FILESYSTEM_DRIVER', 'public'),

Set a symlink from /public/storage to /storage/app/public folder, with a  Artisan command:

php artisan storage:link

Step 6: Show an Avatar Thumbnail

The use of that avatar is to show it on the top-right corner near the user’s name, so let’s do that.

But if the uploaded file is large? How could we resize it to, say, 60×60? This is where Media Library will support us again. All we want to do is set resize rules in the same app >> User model.

use Spatie\MediaLibrary\Models\Media;

class User extends Authenticatable implements HasMedia
{

    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('thumb')
            ->width(60)
            ->height(60);
    }
}

When uploading, this will be automatically stored in conversations sub-folder for that item.

At last, this is how we show the avatar in resources >> views >> layout >> app.blade.php file.

<!--app.blade.php-->

<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
   <img src="{{Auth::user()->getFirstMediaUrl('avatars', 'thumb') }}">
   {{ Auth::user()->name }} <span class="caret"></span>
</a>

Final code of app.blade.php file looks like that.

<!--app.blade.php-->

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li><a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a></li>
                            <li><a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a></li>
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                <img src="{{Auth::user()->getFirstMediaUrl('avatars', 'thumb') }}">
                                {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

 

laravel avatar image upload example

Finally, Our Laravel Avatar Image Upload Tutorial With Example is over. Thanks for taking.

The post Laravel Avatar Image Upload Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/02/laravel-avatar-image-upload-tutorial-with-example/feed/ 5
Laravel Dropzone Image Upload Tutorial With Example https://appdividend.com/2018/05/31/laravel-dropzone-image-upload-tutorial-with-example/ https://appdividend.com/2018/05/31/laravel-dropzone-image-upload-tutorial-with-example/#comments Thu, 31 May 2018 06:06:05 +0000 http://localhost/appdividend/?p=2825 Laravel Dropzone Image Upload Tutorial With Example

Laravel Dropzone Image Upload Tutorial, we will discuss today. Dropzone is the most famous, free and open source library that provides drag and drop file uploads with image previews. In this example, I will be using Laravel 5.6, but you can follow along using previous versions as well. Earn a Tech Degree and get the skills like […]

The post Laravel Dropzone Image Upload Tutorial With Example appeared first on AppDividend.

]]>
Laravel Dropzone Image Upload Tutorial With Example

Laravel Dropzone Image Upload Tutorial, we will discuss today. Dropzone is the most famous, free and open source library that provides drag and drop file uploads with image previews. In this example, I will be using Laravel 5.6, but you can follow along using previous versions as well.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

This tutorial explains the following:

  • Uploading multiple images with dropzone
  • Saving images with different file names to the database
  • Removing images direct from dropzone preview box

Laravel Dropzone Image Upload Tutorial With Example

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel dropzonefileupload

Step 2: Setup a MySQL database

Setup the database in the .env file.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dropzonefileupload
DB_USERNAME=root
DB_PASSWORD=

I have set up local database credentials.

Step 3: Compose a model and migration file

Type the following command in your cmd.

$ php artisan make:model ImageUpload -m

It will create two files.

  1. ImageUpload.php model.
  2. create__image_uploads_table migration file.

We need to create Schema for the image upload table. So navigate to Laravel  >>  database  >>  migrations  >>  create__image_uploads_table.

//create_image_uploads_table

 public function up()
    {
        Schema::create('image_uploads', function (Blueprint $table) {
            $table->increments('id');
            $table->text('filename');
            $table->timestamps();
        });
    }

Step 4: Create a view file

Create a file in resources  >>  views  >>   imageupload.blade.php put this following code in itIn this file, we will be adding dropzone for file uploading.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
</body>
</html>

In this file, we do first add our bootstrap.min.css, dropzone.min.css. Then we are adding jquery.js and dropzone.js. Next, we are creating a form and attaching dropzone class to it. Further, we have some text that will be displayed in our upload box. Also, if that image is uploaded successfully, it will show a tick unless it will display cross and error.

Step 5: Configure Dropzone

Now we write all the configurations for Dropzone. So add following code in a view file.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
<script type="text/javascript">
        Dropzone.options.dropzone =
         {
            maxFilesize: 12,
            renameFile: function(file) {
                var dt = new Date();
                var time = dt.getTime();
               return time+file.name;
            },
            acceptedFiles: ".jpeg,.jpg,.png,.gif",
            addRemoveLinks: true,
            timeout: 5000,
            success: function(file, response) 
            {
                console.log(response);
            },
            error: function(file, response)
            {
               return false;
            }
};
</script>
</body>
</html>

In the file above, we are appending configuration options for Dropzone. You can find any of the configuration options available on the dropzone documentation.

Now let’s go through each option.

  • maxFilesize is set to 12. Dropzone will only allow images with size less than 12MB. You can make it smaller or greater based on your requirements.
  • renameFile function that is invoked before the file is uploaded to the server and renames the file.
  • acceptedFiles checks the file’s mime type or extension against this listWe define .jpeg,.jpg,.png,.gif. You can change based on your needs.
  • addRemoveLinks is set to true. Dropzone will display Remove button to remove our uploaded file.
  • timeout is set to 5000

Step 6: Create one controller and route 

php artisan make:controller ImageUploadController

It will create one controller file called ImageUploadController.php

we register route in routes  >>  web.php file. So let us do it.

//web.php

Route::get('image/upload','ImageUploadController@fileCreate');
Route::post('image/upload/store','ImageUploadController@fileStore');
Route::post('image/delete','ImageUploadController@fileDestroy');

Next step would be to go to ImageUploadController.php file and add to fileCreate() function some code.

// ImageUploadController.php

public function fileCreate()
    {
        return view('imageupload');
    }

In create method, we are simply returning imageupload which we have created.

laravel dropzone file upload example

 

Step 7: Save File into Database

We need coding the fileStore() function in series to store the filename in the database.

//ImageUploadController.php

use App\ImageUpload;

public function fileStore(Request $request)
    {
        $image = $request->file('file');
        $imageName = $image->getClientOriginalName();
        $image->move(public_path('images'),$imageName);
        
        $imageUpload = new ImageUpload();
        $imageUpload->filename = $imageName;
        $imageUpload->save();
        return response()->json(['success'=>$imageName]);
    }

Laravel Multiple Images Uploading with drag and drop using dropzone.js example

Step 8: Remove File From Database

Now, we add removedFile() function in dropzone configuration.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
<script type="text/javascript">
        Dropzone.options.dropzone =
         {
            maxFilesize: 12,
            renameFile: function(file) {
                var dt = new Date();
                var time = dt.getTime();
               return time+file.name;
            },
            acceptedFiles: ".jpeg,.jpg,.png,.gif",
            addRemoveLinks: true,
            timeout: 50000,
            removedfile: function(file) 
            {
                var name = file.upload.filename;
                $.ajax({
                    headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                    type: 'POST',
                    url: '{{ url("image/delete") }}',
                    data: {filename: name},
                    success: function (data){
                        console.log("File has been successfully removed!!");
                    },
                    error: function(e) {
                        console.log(e);
                    }});
                    var fileRef;
                    return (fileRef = file.previewElement) != null ? 
                    fileRef.parentNode.removeChild(file.previewElement) : void 0;
            },
       
            success: function(file, response) 
            {
                console.log(response);
            },
            error: function(file, response)
            {
               return false;
            }
};
</script>
</body>
</html>

Add fileDestroy() function to delete file from database. Add following code in FileUploadController.

//ImageUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\ImageUpload;

class ImageUploadController extends Controller
{
    public function fileCreate()
    {
        return view('imageupload');
    }
    public function fileStore(Request $request)
    {
        $image = $request->file('file');
        $imageName = $image->getClientOriginalName();
        $image->move(public_path('images'),$imageName);
        
        $imageUpload = new ImageUpload();
        $imageUpload->filename = $imageName;
        $imageUpload->save();
        return response()->json(['success'=>$imageName]);
    }
    public function fileDestroy(Request $request)
    {
        $filename =  $request->get('filename');
        ImageUpload::where('filename',$filename)->delete();
        $path=public_path().'/images/'.$filename;
        if (file_exists($path)) {
            unlink($path);
        }
        return $filename;  
    }
}

Finally, Our Laravel Dropzone Image Upload Tutorial With Example is over. Thanks for taking.

 

The post Laravel Dropzone Image Upload Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/31/laravel-dropzone-image-upload-tutorial-with-example/feed/ 11
How To Create Newsletter in Laravel https://appdividend.com/2018/05/24/how-to-create-newsletter-in-laravel/ https://appdividend.com/2018/05/24/how-to-create-newsletter-in-laravel/#comments Thu, 24 May 2018 12:03:53 +0000 http://localhost/appdividend/?p=2769 How To Create Newsletter in Laravel

How To Create Newsletter in Laravel is the topic, we will discuss today. In this example, we use laravel 5.6. We use spatie/laravel-newsletter package for creating a newsletter in laravel. MailChimp is an email marketing service which provides us to send newsletters to our subscribers. Top bloggers and marketers use professional email marketing services to send email newsletters. Email newsletters can help your business attach […]

The post How To Create Newsletter in Laravel appeared first on AppDividend.

]]>
How To Create Newsletter in Laravel

How To Create Newsletter in Laravel is the topic, we will discuss today. In this example, we use laravel 5.6. We use spatie/laravel-newsletter package for creating a newsletter in laravel. MailChimp is an email marketing service which provides us to send newsletters to our subscribers. Top bloggers and marketers use professional email marketing services to send email newsletters. Email newsletters can help your business attach to customers.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

How To Create Newsletter in Laravel

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel newsletter

Step 2: Install Newsletter Package

First, install Newsletter via the Composer package manager.

composer require spatie/laravel-newsletter                                   

The package will automatically register itself.

To publish the config file to config/newsletter.php run:

php artisan vendor:publish --provider="Spatie\Newsletter\NewsletterServiceProvider"

Step 3: Sign Up in MailChimp

First, you sign up in MailChimp. If you have already account then sign in.

Step 4: Get MailChimp API Key And List Id

After successfully sign up or sign we can get api key and list id. So follow this image.

Laravel Newsletter Tutorial

You can see below screen. Then move to Extras >> API keys.

Laravel Newsletter Example

Under the Your API keys section, tick on Create A Key and copy your API key which we want in a minute.

 

laravel newsletter mailchimp tutorial

After successfully generate api key now we can get list id so follow below image to get list id.

 

How To Integrate Newsletter in Laravel

Click on List name and defaults, and you get to list id in below image.

How to Generate Newsletter in Laravel

Step 5: Set API Key And List Id in .env file

Next, we set up api key and id in the .env file.

//.env

MAILCHIMP_APIKEY=xxxx
MAILCHIMP_LIST_ID=xxxx

Step 6: Create a view file

Create a file in resources  >>  views  >>   newsletter.blade.php and put this following code in it.

<!-- newsletter.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Newsletter Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
  </head>
  <body>
    <div class="container">
    @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
     @if (\Session::has('failure'))
      <div class="alert alert-danger">
        <p>{{ \Session::get('failure') }}</p>
      </div><br />
     @endif
      <h2>Laravel Newsletter Tutorial With Example</h2><br/>
      <form method="post" action="{{url('newsletter')}}">
        @csrf
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-2">
              <label for="Email">Email:</label>
              <input type="text" class="form-control" name="email">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

Step 7: Create a Controller and route

php artisan make:controller NewsletterController                              

It will build a controller file called NewsletterController.php.

Add following code to the controller.

//NewsletterController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Newsletter;

class NewsletterController extends Controller
{
    public function create()
    {
        return view('newsletter');
    }

    public function store(Request $request)
    {
        if ( ! Newsletter::isSubscribed($request->email) ) 
        {
            Newsletter::subscribePending($request->email);
            return redirect('newsletter')->with('success', 'Thanks For Subscribe');
        }
        return redirect('newsletter')->with('failure', 'Sorry! You have already subscribed ');
            
    }
}

We register route in a web.php file.

Route::get('newsletter','NewsletterController@create');
Route::post('newsletter','NewsletterController@store');

Laravel Newsletter Tutorial with Example

You can see that alert message Thanks For Subscribe then you move to your mail and see the inbox you have to look at below image like mail.

laravel 5.6 newsletter tutorial

Finally, Our How To Create Newsletter in Laravelis over. Thanks for taking.

The post How To Create Newsletter in Laravel appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/24/how-to-create-newsletter-in-laravel/feed/ 3
Laravel Cloud File Upload Tutorial With Example https://appdividend.com/2018/05/22/laravel-cloud-file-upload-tutorial-with-example/ https://appdividend.com/2018/05/22/laravel-cloud-file-upload-tutorial-with-example/#comments Tue, 22 May 2018 05:01:09 +0000 http://localhost/appdividend/?p=2733 Laravel Cloud File Upload Tutorial With Example

Laravel Cloud File Upload Tutorial With Example is the topic, we will discuss today. For this example, we use laravel 5.6 and Amazon s3 package for upload file to aws s3. Laravel gives a powerful filesystem abstraction thanks to the Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides easy to use drivers for working […]

The post Laravel Cloud File Upload Tutorial With Example appeared first on AppDividend.

]]>
Laravel Cloud File Upload Tutorial With Example

Laravel Cloud File Upload Tutorial With Example is the topic, we will discuss today. For this example, we use laravel 5.6 and Amazon s3 package for upload file to aws s3.

Laravel gives a powerful filesystem abstraction thanks to the Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides easy to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it’s amazingly easy to switch between these storage options as the API rests the same for each system.

Amazon S3 stores data as objects inside resources called “buckets.” You can store as multiple objects as you require within a bucket, and read, write, and delete objects in your bucket. Objects can do up to 5 terabytes in size. You can store images, files or other documents.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

Laravel Cloud File Upload Tutorial With Example

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel cloudimageupload

Step 2: Setup s3 bucket

We use amazon s3 to store our images. First, we need to sign up to Amazon. You should follow this link to signup.  After successfully signing you can create your bucket. You can see below image for clarification.

laravel cloud file upload example

Now we need to generate bucket policy so move to this link http://awspolicygen.s3.amazonaws.com/policygen.html 

You can see the page like this.

laravel s3 bucket policy

 

Inside bucket, you create one folder called images.

Then you generate policy and copy paste into bucket policy. You can see below image.

laravel s3 file upload tutorial

 

We have added bucket policy now I already start uploading images to this folder which can be publicly accessible.

Step 3: Setup Cloud Storage

Remember to put your API Key and Secret Key in your .env file. You can add the following field in your .env file.

1.Access Key

2.Secret Access Key

3.Region

4.Bucket

//.env

AWS_ACCESS_KEY_ID=xxxxx
AWS_SECRET_ACCESS_KEY=xxxx
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=laravelimage

You can get access key and secret access key from My security Credentials. You can see the page looks like that.

laravel s3 file upload example

 

Then go to user, and a create user after you can generate credentials.

Step 4: Install s3 package

First, install s3 package via the Composer package manager.

composer require league/flysystem-aws-s3-v3

Step 5: Create a View File

Create a file in resources  >>  views  >>  uploadimage.blade.php and put this following code in it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Cloud File Upload Tutorial</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
  </head>
  <body>
    <div class="container">
      <h2>Laravel Cloud File Upload Tutorial</h2><br/>
      @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
     @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <form method="post" action="{{url('createimage')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <input type="file" name="image">    
         </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Upload</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

Step 6: Create a Controller and route

 php artisan make:controller ImageController

It will build a controller file called ImageController.php.

Add following code to the controller.

//Imageontroller.php

public function create()
    {
        return view('uploadimage');
    }

We register all route in a web.php file.

Route::get('createimage','ImageController@create');
Route::post('createimage','ImageController@imageUpload');

Step 7: Create a function to upload an image

We create a function in ImageController called imageUpload(). 

Now we want to create a new S3 Filesystem instance, define the path related to our bucket, and upload the file. We will use the put() method and pass three parameters.

  1. File path relative to your bucket
  2. The contents of the file
  3. Permission of the file (optional)
//ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;

class ImageController extends Controller
{
    public function create()
    {
        return view('uploadimage');
    }
    public function imageUpload(Request $request)
    {
        $this->validate($request, ['image' => 'required|image']);
        if($request->hasfile('image'))
         {
            $file = $request->file('image');
            $name=time().$file->getClientOriginalName();
            $filePath = 'images/' . $name;
            Storage::disk('s3')->put($filePath, file_get_contents($file));
            return back()->with('success','Image Uploaded successfully');
         }
    }
}

You can see below the image that file has been uploaded successfully in Amazon s3.

 

laravel 5.6 s3 file upload tutorial

Finally, Our Laravel Cloud File Upload Tutorial With Example is over. Thanks for taking.

The post Laravel Cloud File Upload Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/22/laravel-cloud-file-upload-tutorial-with-example/feed/ 1
Laravel Polymorphic Relationship Tutorial Example https://appdividend.com/2018/05/18/laravel-polymorphic-relationship-tutorial-example/ https://appdividend.com/2018/05/18/laravel-polymorphic-relationship-tutorial-example/#comments Fri, 18 May 2018 12:40:40 +0000 http://localhost/wordpress/?p=825 Laravel Polymorphic relationship tutorial with example

Laravel Polymorphic Relationship Tutorial Example is the today’s leading topic. Polymorphic relations allow a model to belong to more than one other model on a single association. We will take an official Laravel documentation example for this tutorial. Let us take an example of “comment” both posts and videos. Using polymorphic relationships, you can use a single comments table for […]

The post Laravel Polymorphic Relationship Tutorial Example appeared first on AppDividend.

]]>
Laravel Polymorphic relationship tutorial with example

Laravel Polymorphic Relationship Tutorial Example is the today’s leading topic. Polymorphic relations allow a model to belong to more than one other model on a single association. We will take an official Laravel documentation example for this tutorial. Let us take an example of “comment” both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

There are total three tables.

  1. posts
  2. videos
  3. comments

Now, the reason we can apply the Polymorphic Relationship here is that comment can be applied to both posts and videos.

So, Comment model can be associated with Post and Video.

Now, we need to add two extra columns inside posts table.

  1. commentable_id (Integer)
  2. commentable_type (String)

The commentable_id column will contain the ID value of the post or video.

The commentable_type column will contain the class name of the owning model. 

Now, let us start practice on Laravel Polymorphic Relationship Tutorial Example.

Laravel Polymorphic Relationship Tutorial Example

We start our project by installing the Laravel project.

Step 1: Install Laravel 5.6

Type the following command in your terminal.

laravel new relationships

# or

composer create-project laravel/laravel relationships --prefer-dist

After installation, go into the project.

cd relationships

Open the project in your code editor.

code .

Setup the database inside the .env file.

Now, create an Authentication scaffold using the following command.

php artisan make:auth

Step 2: Create the models and migrations.

Go to your terminal and first create Post model.

php artisan make:model Post -m

Also, we create a Video model.

php artisan make:model Video -m

Now, define the schema for both of the migrations. First, let us define a schema for create_posts_table.

// create_posts_table

public function up()
{
   Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

Now define a schema for the create_videos_table.

// create_videos_table

public function up()
{
     Schema::create('videos', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');            
         $table->timestamps();
     });
}

Okay, now migrate using the following command.

php artisan migrate

Step 3: Create two controller files.

Okay, now we will create two controllers to render the views.

  1. PostController
  2. VideoController

Type the following command to generate it.

php artisan make:controller PostController
php artisan make:controller VideoController

 Now, write the following code inside PostController.php file.

// PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function show(Post $post)
    {
        return view('post.show', compact('post'));
    }
}

Same for, VideoController.php file.

// VideoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Video;

class VideoController extends Controller
{
    public function show(Video $video)
    {
        return view('video.show', compact('video'));
    }
}

Now, create two folders inside views folder.

  1. post
  2. video

Inside post folder, create a new file called show.blade.php file. Also, same create same show.blade.php file inside video folder.

Step 4: Define routes to show the Post and Video.

Inside web.php file, write the following code.

// web.php

Route::get('/post/{post}', 'PostController@show')->name('post.show');
Route::get('/video/{video}', 'VideoController@show')->name('video.show');

Now, enter the data manually in the database. In real-time, the data is coming from a form, but for this demo, First, enter some dummy data in the posts table.

Laravel Polymorphic Relationship Tutorial Example

 

Now, insert the data into the videos table.

Polymorphic Relationship in Laravel

 

So, we have inserted dummy data in both the tables.

Step 5: Code the view files.

Inside post  >>  show.blade.php file, write the following code.

<h3>{{ $post->name }}</h3>

Now, go to the browser and type this URL: http://relationships.test/post/1. You can see the 1st post.

Same for the video  >>  show.blade.php file, write the following code.

<h3>{{ $video->name }}</h3>

Same, go to the browser and hit this URL: http://relationships.test/video/1. You can see the 1st video.

Step 6: Create a Comment model.

Type the following command to generate model as well as migration.

php artisan make:model Comment -m

Now, write the following schema inside create_comments_table.

// create_comments_table

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('user_id')->unsigned();
         $table->text('body');
         $table->integer('commentable_id')->unsigned();
         $table->string('commentable_type');
         $table->timestamps();
    });
}

Migrate that schema in the database.

php artisan migrate

Step 7: Define the relationships.

Now, we store a user_id inside comments table; we have a relationship with the User.

A Comment is belongsTo User. So we can write this relationship inside Comment.php model file.

// Comment.php

public function user()
{
    return $this->belongsTo(User::class);
}

Okay, now we write one more function inside Comment.php file, and that is commentable().

// Comment.php

public function commentable()
{
    return $this->morphTo();
}

Now this means that now one or more models can use this Comment model. In our example, It can be associated with Post and Video. Both use this same Comment model.

Okay, so next step is the post model has many comments. So we can define the relationship inside Post.php file like this.

// Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Also, same for Video.php file.

// Video.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Step 8: Insert manual data inside comments table.

We have set up all the relationships. Now, we just need to enter the demo comments and see, if we get the comments on video and post’s show page.

Polymorphic hasMany Relationship

 

So, the first column is id, as usual, auto-increments, second is user_id, which is currently signed user.

The third column is commentable_id, in our case, it is either post table’s id or video table’s id.

So, we have attached posts and videos tables to their respective comments.

Now, render the post with their comments in the show.blade.php file.

<h3>{{ $post->name }}</h3>

<ul>
    @foreach($post->comments as $comment)
    <li>{{ $comment->body }}</li>
    @endforeach
</ul>

Go to the browser and hit this URL: http://relationships.test/post/1. You can see the post name and comment body. 

You can write same view file for the video  >>  show.blade.php.

<h3>{{ $video->name }}</h3>

<ul>
    @foreach($video->comments as $comment)
    <li>{{ $comment->body }}</li>
    @endforeach
</ul>

Now, test this URL: http://relationships.test/video/1.

That is it; we have successfully displayed the post and video with their respective comments.

Although, in this example, I have inserted hardcode values, but we will see programmatically in future.

Finally, Laravel Polymorphic Relationship Tutorial is over.

The post Laravel Polymorphic Relationship Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/18/laravel-polymorphic-relationship-tutorial-example/feed/ 2
Laravel HasManyThrough Relationship Example https://appdividend.com/2018/05/18/laravel-hasmanythrough-relationship-example/ https://appdividend.com/2018/05/18/laravel-hasmanythrough-relationship-example/#comments Fri, 18 May 2018 07:35:04 +0000 http://localhost/wordpress/?p=803 Laravel 5.6 hasManyThrough Relationship Tutorial with Example From Scratch

In this tutorial, we will see Laravel HasManyThrough Relationship Example. The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. The first argument passed to the hasManyThrough function is the name of the final model we wish to access, while the second argument is the name of the intermediate model. At first, this relationship […]

The post Laravel HasManyThrough Relationship Example appeared first on AppDividend.

]]>
Laravel 5.6 hasManyThrough Relationship Tutorial with Example From Scratch

In this tutorial, we will see Laravel HasManyThrough Relationship Example. The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. The first argument passed to the hasManyThrough function is the name of the final model we wish to access, while the second argument is the name of the intermediate model. At first, this relationship is complicated. So let us bring it down to small pieces.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

Let us say; we have three models.

  1. Team (id, user_id, name)
  2. User (id, name)
  3. Goal (id, user_id, no.of goals)

So, the relationship is like this.

Team hasMany User (team_id inside User model)

User hasMany Goal (user_id inside Goal model)

See, from the relationship, we can see that here, the User model is an intermediary model.

We can not store the goal_id directly to the Team table because we already store the goal_id in the User table.

So, now User model is in a relationship with the Team model. So, inside User model there is team_id.

Finally, if we need to access how many goals the Team has created then, we can go through User model.

If that type of scenario is generated for your use case then and then you need to define this type of relationship.

Okay, now let us see the Practical Implementation of that Laravel HasManyThrough Relationship.

Laravel HasManyThrough Relationship Example

As always, start our project by installing fresh Laravel.

Step 1: Install Laravel 5.6.

laravel new relationships

Now, go into the project folder.

cd relationships

Open the project in your editor.

code .

Configure the database in the .env file.

Step 2: Create migrations.

Now, as we have discussed earlier, we need to define the team_id inside User table, so let us first add the team_id inside users migration.

// create_users_table

public function up()
{
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('team_id')->unsigned();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
}

Next, create another model with migration call Team.

php artisan make:model Team -m

Define the following schema inside create_teams_table.

// create_teams_table

public function up()
{
    Schema::create('teams', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

Finally, create another model called Goal with its migration.

php artisan make:model Goal -m

Also, write the following schema in the migration file.

// create_goals_table

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('goals', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('number_of_goals')->unsigned();
            $table->timestamps();
        });
    }

Now, finally, migrate the schema files using the following command.

php artisan migrate

Step 3: Create a User with team_id.

First, create an auth scaffold using the following command.

php artisan make:auth

Now, we need to Register a User, but the default Laravel register code does not save the team_id. So, we need to manually add the team_id.

Inside app >> Http  >> Auth  folder, you can see a RegisterController.php file. In that file, add one more column inside create() function.

// RegisterController.php

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
         'team_id' => 1
    ]);
}

Also, add the column inside a protected $fillable property in User.php file.

// User.php

protected $fillable = [
    'name', 'email', 'password','team_id'
];

Now, register one user by this URL: http://relationships.test/register

I have registered the four users with team_id. Although, we will create demo teams in next step.

Laravel HasManyThrough Relationship

 

Step 4: Create teams manually inside a database.

We have defined the team_id inside users table but did not have created yet, so let us do that first.

hasManyThrough relationship in Laravel

Step 5: Create goals manually inside a database.

Also, we need to assign the user_id inside goals table, while creating the goals.

hasmanythrough laravel example

 

Step 6: Define the relationships inside models.

Now, inside User.php file. we can define the following relationships.

  1. User hasMany Goals.
  2. User belongsTo Team.
// User.php

public function goals()
{
    return $this->hasMany(Goal::class);
}

public function team()
{
    return $this->belongsTo(Team::class);
}

Next step inside Goal.php file, we can define the following relationship.

  1. Goal belongsTo User
// Goal.php

public function user()
{
     return $this->belongsTo(User::class);
}

Finally, inside Team.php, we can define the following relationship.

  1. Team hasMany User
// Team.php

public function users()
{
     return $this->hasMany(User::class);
}

Step 7: Create a Controller file.

Okay, till now, we have created the migrations and models. We have also defined the relationship between the models. Now, we need to display the data based on defined relationships.

php artisan make:controller TeamController

Now, inside TeamController.php file, define the show() function.

We are using implicit model binding to show a particular team’s data.

// TeamController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class TeamController extends Controller
{
    public function show(Team $team)
    {
        dd($team);
    }
}

Define the route for show function inside a web.php file.

// web.php

Route::get('/team/{team}', 'TeamController@show')->name('team.show');

Now, go to this URL: http://relationships.test/team/1.

We have die to dump the object, so we get all the information about the team object that has an ID: 1.

So, we get the different teams based on the passing id.

Our primary goal is to check all the goals; the team has created.

However, the goal_id is not associated directly with the Team model.

The goal_id associated with the User model.

So, what we can do is that we can collect all the goals through the User model.

In that case, we can define the relationship like below inside Team.php model.

// Team.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    public function users()
    {
        return $this->hasMany(User::class);
    }

    public function goals()
    {
        return $this->hasManyThrough(Goal::class, User::class);
    }
}

Now, you call the goals() function from the TeamController.php file.

// TeamController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class TeamController extends Controller
{
    public function show(Team $team)
    {
        $goals = $team->goals()->get();

        return view('team.show', compact('goals'));
    }
}

Create a folder called team inside views and inside that folder, create one blade file called show.blade.php.

Write the following code inside show.blade.php file.

<h3>The team has scored following goals</h3>

@foreach($goals as $goal)
    <p>{{ $goal->number_of_goals }}</p>
@endforeach

Go to this URL: http://relationships.test/team/1

Eloquent hasManyThrough Relationship

 

You can verify this by going to first teams table and pick the ID: 1.

Now, go to the User’s table and see, which users are belongsTo that team_id: 1.

Take those ids and verify the goals inside goals table because it goals table has user_id.

So, this is how you can build up a hasManyThrough relationship in Laravel.

Finally, Laravel HasManyThrough Relationship is over.

The post Laravel HasManyThrough Relationship Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/18/laravel-hasmanythrough-relationship-example/feed/ 1
Laravel Many To Many Relationship Example https://appdividend.com/2018/05/17/laravel-many-to-many-relationship-example/ https://appdividend.com/2018/05/17/laravel-many-to-many-relationship-example/#comments Thu, 17 May 2018 12:14:53 +0000 http://localhost/wordpress/?p=789 Laravel Many To Many Eloquent Relationship With Example From Scratch

In this tutorial, we will see Laravel Many To Many Relationship Example. Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.  Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany.  Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a […]

The post Laravel Many To Many Relationship Example appeared first on AppDividend.

]]>
Laravel Many To Many Eloquent Relationship With Example From Scratch

In this tutorial, we will see Laravel Many To Many Relationship Example. Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.  Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany. 

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

In our example, we will define the two models.

  1. Category
  2. Product

In our example, Multiple Categories have Multiple Products, and an inverse relationship will be Multiple Products belongs to Multiple Categories.

So, what we can do is that, when we go to the particular Category, we need to display all the Products.

Same, when we see the particular Product, then we do need to display all the Categories that belongs to that specific Product.

Let us take a Laravel Many To Many Relationship Example and start working on that.

Laravel Many To Many Relationship Example

We start this example, by installing the Laravel 5.6 project.

Step 1: Install Laravel 5.6.

I am using Laravel Valet so that I will create a new project using the following command.

laravel new relationships

Now, if you are not using Laravel Valet then, install using the following command.

composer create-project laravel/laravel relationship --prefer-dist

Go into the project.

cd relationships

Open the project in your editor.

code .

First thing, set up the database.

Step 2: Create a model and migration.

We are defining two models for our example.

  1. Category
  2. Product
php artisan make:model Category -m
php artisan make:model Product -m

It will create products and categories tables and models.

Now, inside create_categories_table, define the following schema.

// create_categories_table

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

Also, write the following schema inside create_products_table.

// create_products_table

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->float('price');
            $table->timestamps();
        });
    }

Now, go to the terminal and create the tables using the following command.

php artisan migrate

Step 3: Define random categories manually.

In this example, we are just focusing on, how many to many relationships works, how we can assign the values and create a relationship with one to another table. So, we create three categories manually inside the database table.

Laravel Many To Many Relationship

 

So, we have manually defined three categories.

Step 4: Define Pivot table.

We have already defined two table schemas 1) Category 2) Product.

Now, we need to define the third table, which is Pivot table. 

The Pivot table is the relationship between two tables.

So Pivot table have these columns.

  1. id
  2. category_id
  3. product_id

Now, we are creating Many to Many relationships, that is why any number of products have any number of categories. To create a migration file, type the following command.

php artisan make:migration create_category_product_table --create=category_product

Now, define the following schema in the migration file.

// create_category_product_table

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->integer('product_id')->unsigned();
        });
    }

Now, migrate using the following command.

php artisan migrate

Step 5: Define the relationships.

Now, Multiple Categories belongs to Multiple Products. So inside Product.php file, we can define the belongsToMany relationship.

// Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
}

Also, same for the products. Multiple Products belongs To Multiple Categories. So inside Category.php file, we can define the belongsToMany relationship.

// Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Product;

class Category extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}

So, we have defined the relationship between them.

Now, let us create a new product and assign the Category to the Product.

Step 6: Create a Product.

In a real-time scenario, we create a form and then through POST request, we insert the Product data into the table. However, in this example, we will not define any form, we directly store the data into the database, because our goal is how we can use many to many relationships to the complex scenario.

Now, define a route that saves the product into the database as well as assigns the product to the category using many to many relationships. Now, we have four(4) categories. So, we create a product and assign the two categories to one product.

First, create a ProductController using the following command.

php artisan make:controller ProductController

Next step, define the route to store the product.

Now, I am using GET request for the saving the data because, we have not created the form, so we take every data manually.

// ProductController.php

Route::get('product/create', 'ProductController@create')->name('product.create');

Import both the models in this ProductController.php file.

Also, Now, what we are going to do is that we will create one Product that belongs To Many Categories.

In this example tutorial, we are going to create a Product called God of War.

Now, God of War belongs to two categories.

  1. Video Games
  2. Playstation

So, when we create a product, we also need to fill the pivot table with the two categories.

So, our product_id will be one but, the category_id will be different so that it will create two rows in the category_product table.

Now, write the following code inside ProductController’s create() function.

// ProductController.php

<?php

namespace App\Http\Controllers;
use App\Category;
use App\Product;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function create(Request $request)
    {
        $product = new Product;
        $product->name = 'God of War';
        $product->price = 40;

        $product->save();

        $category = Category::find([3, 4]);
        $product->categories()->attach($category);

        return 'Success';
    }
}

Explanation.

First, we have created the product and save in the products table.

Now, it is time, to assign the categories to the newly created product.

Since we just need an ID of categories, so right now, I have coded manually, but in real-time, you have those ids in the form request.

Now, attach() function will assign those category ids to the newly created product and also create two new rows inside pivot table. Each row has a relationship with its product and category.

Next step is going to this URL: http://relationships.test/product/create or http://localhost:8000/product/create

You can see the “Success.”

Now, go to the database and see the products table.

Many To Many Relationship in Laravel

 

Also, you can check the Pivot Table, and that is a create_product table.

If we have done all correctly, then we can see the two rows inside the table, where product_id is the same 1 for both the rows, but category_id’s are different, and that is and 4.

Laravel 5.6 Many To Many Relationships

 

Yayy!!, we have successfully attached the two categories to one product.

Next step is to display the Product Information and in that, display all the Categories inside that Product.

Step 7: Display the Product Information.

Define the route that can display all the information.

// web.php

Route::get('product/{product}', 'ProductController@show')->name('product.show');

Now, define the ProductController’s show function.

In this function, I am using Routing Model Binding.

// ProductController.php

public function show(Product $product)
{
   return view('product.show', compact('product'));
}

Whatever we pass the product id in the get request, we fetch the product details via Route Model Binding directly and pass that product detail to the view.

Create a new folder inside views folder called products and inside that, create one file called show.blade.php.

Write the following code inside show.blade.php file. We display the product name, price and belongs to categories.

// show.blade.php

<h2>Product Name: </h2>
<p>{{ $product->name }} || ${{ money_format($product->price, 2) }}</p>

<h3>Product Belongs to</h3>

<ul>
    @foreach($product->categories as $category)
    <li>{{ $category->title }}</li>
    @endforeach
</ul>

As we have defined the relationship, we can directly fetch all the categories from the Product model, and that is the magic of Eloquent Relationships in the Laravel.

Now, go to this URL: http://relationships.test/product/1 or http://localhost:8000/product/1

As you can see that, we have only one product created so that we can see only One product detail.

 

Laravel attach() function

So, this is how you can add the multiple categories to a product and display multiple categories for a product.

Now, you can create as many products as you want and assign multiple categories to it.

You can also delete the relationship between the tables using the detach() function.

Detach() function.

// ProductController.php

public function removeCategory(Product $product)
{
        $category = Category::find(3);

        $product->categories()->detach($category);
        
        return 'Success';
}

Now, define the following route inside a web.php file.

// web.php

Route::get('category/product/{product}', 'ProductController@removeCategory')->name('category.product.delete');

Next, type this URL: http://relationships.test/category/product/1 or http://localhost:8000/category/product/1

Hit enter, and we get success, now hover to the MySQL database and check the category_product table.

You can see that the category_id = 3 row is deleted and we are no longer belongs to category_id = 3.

 

Laravel detach() Function

So, this is how you can maintain the many to many relationships in Laravel.

Finally, our Laravel Many To Many Relationship example tutorial is over.

The post Laravel Many To Many Relationship Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/17/laravel-many-to-many-relationship-example/feed/ 8