ساخت follow برای کاربران در لاراول

۲۴ فروردین ۱۳۹۶

Following User

اول برای follow یک مدل می سازیم به فرمان زیر توجه کنید:

php artisan make:model Follow -m

با دستور بالا همزمان migration آن هم ایجاد می کنیم و migration خود را با دستورات زیر می سازیم:

public function up()
{
    Schema::create('follows', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->index();
        $table->integer('target_id')->index(); // ID of person being followed
        $table->timestamps();
    });
}

حالا با دستور زیر جدول follows را می سازیم.

php artisan migrate

حالا در مدل app/User.php با جدول follows ارتباط برقرار می کنیم:

[...]
class User extends Authenticatable
{
    [...]
    public function follows() {
        return $this->hasMany(Follow::class);
    }
}

وهمچنین در مدل app/Follow.php با جدول users ارتباط برقرار می کنیم:

[...]
class Follow extends Model
{
    protected $fillable = ['target_id'];

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

حالا در قسمت روتها کدهای زیر را اضافه می کنیم:

    [...]
Route::group(['middleware' => ['auth']], function () {
    [...]
    Route::get('/users', 'FollowController@index');
    Route::post('/follow/{user}', 'FollowController@follow');
    Route::delete('/unfollow/{user}', 'FollowController@unfollow');
});
[...]

حالا با دستور زیر کنترلر FollowController را اضافه می کنیم:

    php artisan make:controller FollowController

حالا به آدرس app/Http/Controllers/FollowController.php رفته و متد index را اضافه می کنیم:

    [...]
use App\User;
use App\Follow;
use Illuminate\Support\Facades\Auth;
[...]

class FollowController extends Controller
{
    public function index()
    {
        return view('users.index', [
            'users' => User::where('id', '!=', Auth::id())->get()
        ]);
    }
}

حالا در قسمت view فایل resources/views/users/index.blade.php را ایجاد کرده و کدهای زیر را داخل آن قرار می دهیم:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="col-sm-offset-2 col-sm-8">

            
            <div class="panel panel-default">
                <div class="panel-heading">
                    All Users
                div>

                <div class="panel-body">
                    <table class="table table-striped task-table">
                        <thead>
                            <th>Userth>
                            <th> th>
                        thead>
                        <tbody>
                            @foreach ($users as $user)
                                <tr>
                                    <td clphpass="table-text"><div>{{ $user->name }}div>td>
                                tr>
                            @endforeach
                        tbody>
                    table>
                div>
            div>
        div>
    div>
@endsection

سپس در مدل app/User.php متد زیر را اضافه می کنیم:

    class User extends Authenticatable
{
    [...]
    public function isFollowing($target_id)
    {
        return (bool)$this->follows()->where('target_id', $target_id)->first(['id']);
    }
}

سپس در کنترلر app/Http/Controllers/FollowController.php متدهای زیر را اضافه می کنیم:

    class FollowController extends Controller
{
    [...]
    public function follow(User $user)
    {
        if (!Auth::user()->isFollowing($user->id)) {
            // Create a new follow instance for the authenticated user
            Auth::user()->follows()->create([
                'target_id' => $user->id,
            ]);

            return back()->with('success', 'You are now friends with '. $user->name);
        } else {
            return back()->with('error', 'You are already following this person');
        }

    }

    public function unfollow(User $user)
    {
        if (Auth::user()->isFollowing($user->id)) {
            $follow = Auth::user()->follows()->where('target_id', $user->id)->first();
            $follow->delete();

            return back()->with('success', 'You are no longer friends with '. $user->name);
        } else {
            return back()->with('error', 'You are not following this person');
        }
    }
}

و همچنین در ویو resources/views/users/index.blade.php کدهای زیر را وارد می کنیم:

[...]
@if (Auth::User()->isFollowing($user->id))
    <td>
        <form action="{{url('unfollow/' . $user->id)}}" method="POST">
            {{ csrf_field() }}
            {{ method_field('DELETE') }}

            <button type="submit" id="delete-follow-{{ $user->target_id }}" class="btn btn-danger">
            <i class="fa fa-btn fa-trash"></i>Unfollow
            </button>
        </form>
    </td>
@else
    <td>
        <form action="{{url('follow/' . $user->id)}}" method="POST">
            {{ csrf_field() }}

            <button type="submit" id="follow-user-{{ $user->id }}" class="btn btn-success">
            <i class="fa fa-btn fa-user"></i>Follow
            </button>
        </form>
    </td>
@endif
[...]

 نویسنده:حمید شاه محمدی
 تعداد مشاهده خبر:(580)
 هر روز از مقاله های جدید طراحی سایت در کانال تلگرام ما با خبر شوید

 میانگین امتیازات:
 
  تعداد رای دهندگان: {{ count }}
نظرات:

{{ x }}
{{ alert }}

نویسنده:{{ com.name }}
{{ com.body }}
{{ com.created_at }}