ErrorException Аргумент 1 передан (Laravel 5.2)

Итак, я пытаюсь "лайкнуть" статус, и когда я это делаю, я получаю взамен эту ошибку.

ErrorException in User.php line 107:
Argument 1 passed to SCM\User::hasLikedStatus() must be an instance of Status, instance of SCM\Status given, called in C:\xampp\htdocs\app\Http\Controllers\StatusController.php on line 66 and defined

Когда я удаляю "использовать статус"; из моего User.php функция работает, и она обновила мою базу данных с таким же идентификатором. Может ли это быть из-за того, что я связал публичную функцию своего статуса, такую ​​как «SCM \ Status»?

Routes.php

<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/


/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => ['web']], function () {
    Route::get('/login', function () {
    return view('auth/login');
});
    Route::get('/register', function () {
    return view('auth/login');
});
    /**
    *User Profile
    */

    Route::get('/user/{username}', [
        'as' => 'profile.index', 'uses' => 'ProfileController@getProfile'
]);
    Route::get('/profile/edit', [
        'uses' => 'ProfileController@getEdit', 'as' => 'profile.edit', 'middleware' => ['auth'],
]);

    Route::post('/profile/edit', [
        'uses' => 'ProfileController@postEdit', 'middleware' => ['auth'],
]);

    Route::get('/settings', [
        'uses' => 'ProfileController@getEdit', 'as' => 'layouts.-settings', 'middleware' => ['auth'],
]);

    Route::post('/settings', [
        'uses' => 'ProfileController@postEdit', 'middleware' => ['auth'],
]);
    /**
    * Friends
    */

    Route::get('/friends', [
        'uses' => 'FriendController@getIndex', 'as' => 'friend.index', 'middleware' => ['auth'],
]);

    Route::get('/friends/add/{username}', [
        'uses' => 'FriendController@getAdd', 'as' => 'friend.add', 'middleware' => ['auth'],
]);
    Route::get('/friends/accept/{username}', [
        'uses' => 'FriendController@getAccept', 'as' => 'friend.accept', 'middleware' => ['auth'],
]);
    /**
    * Statuses
    */

Route::post('/status', [
    'uses' => 'StatusController@postStatus', 'as' => 'status.post', 'middleware' => ['auth'],

]);

Route::post('/status/{statusId}/reply', [
    'uses' => 'StatusController@postReply', 'as' => 'status.reply', 'middleware' => ['auth'],

]);

Route::get('/status/{statusId}/like', [
    'uses' => 'StatusController@getLike', 'as' => 'status.like', 'middleware' => ['auth'],

]);
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/', [
    'as' => 'welcome', 'uses' => 'WelcomeController@index'
]);

    Route::get('/profile', function () {
    return view('layouts/-profile');
});

    Route::get('profile/{username}', function () {
    return view('layouts/-profile');
});




    Route::get('/home', 'HomeController@index');
});

/**
* Search
*/
Route::get('/search', [
    'as' => 'search.results', 'uses' => 'SearchController@getResults'
]);

User.php (модель)

<?php

namespace SCM;

use Status;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $primaryKey = 'id';

    public function getAvatarUrl()
    {
        return "http://www.gravatar.com/avatar/{{ md5 ($this->email)}}?d=mm&s=40 ";
    }

    public function statuses()
    {
        return $this->hasMany('SCM\Status', 'user_id');
    }

    public function likes()
    {
        return $this->hasMany('SCM\Like', 'user_id');
    }

    public function friendsOfMine()
    {
        return $this->belongsToMany('SCM\User', 'friends', 'user_id', 'friend_id');
    }

    public function friendOf()
    {
        return $this->belongsToMany('SCM\User', 'friends', 'friend_id', 'user_id');
    }

    public function friends()
    {
        return $this->friendsOfMine()->wherePivot('accepted', true)->get()->
            merge($this->friendOf()->wherePivot('accepted', true)->get());
    }

    public function friendRequests()
    {
        return $this->friendsOfMine()->wherePivot('accepted', false)->get();

    }

    public function friendRequestsPending()
    {
        return $this->friendOf()->wherePivot('accepted', false)->get();

    }

    public function hasFriendRequestPending(User $user)
    {
        return (bool) $this->friendRequestsPending()->where('id', $user->id)->count();

    }

    public function hasFriendRequestReceived(User $user)
    {
        return (bool) $this->friendRequests()->where('id', $user->id)->count();

    }

    public function addFriend(User $user)
    {
        $this->friendOf()->attach($user->id);

    }

    public function acceptFriendRequest(User $user)
    {
        $this->friendRequests()->where('id', $user->id)->first()->pivot->update([

            'accepted' => true,

        ]);

    }

    public function isFriendsWith(User $user)

    {
        return (bool) $this->friends()->where('id', $user->id)->count();
    }

    public function hasLikedStatus(Status $status)
    {
        return (bool) $status->likes
        ->where('likeable_id', $status->id)
        ->where('likeable_type', get_class($status))
        ->where('user_id', $this->id)
        ->count();
    }
}

Status.php (модель)

<?php

namespace SCM;

use Illuminate\Database\Eloquent\Model;

class Status extends Model
{
    protected $table = 'statuses';

    protected $fillable = [
        'body'
    ];

    public function user()
    {
        return $this->belongsTo('SCM\User', 'user_id');
    }

    public function scopeNotReply($query)
    {
        return $query->whereNull('parent_id');
    }

    public function replies()
    {
        return $this->hasMany('SCM\Status', 'parent_id');
    }

    public function likes()
    {
        return $this->morphMany('SCM\Like', 'likeable');
    }
}

Likes.php (модель)

<?php

namespace SCM;

use Illuminate\Database\Eloquent\Model;

class Like extends Model
{
    protected $table = 'likeable';

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

    public function user ()
    {
        return $this->belongsTo('SCM\User', 'user_id');
    }
}

StatusController.php

<?php

namespace SCM\Http\Controllers;

use Flash;
use Auth;
use Illuminate\Http\Request;
use SCM\User;
use SCM\Status;

class StatusController extends Controller
{
    public function postStatus(Request $request)
    {
        $this->validate($request, [
            'status' => 'required|max:1000',
        ]);

        Auth::user()->statuses()->create([
            'body' => $request->input('status'),
        ]);

        return redirect()->route('welcome')->with('info', 'Status posted.');
    }

    public function postReply(Request $request, $statusId)
    {
        $this->validate($request, [
                "reply-{$statusId}" => 'required|max:1000',
        ], [
            'required' => 'The reply body is required.'
        ]);

        $status = Status::notReply()->find($statusId);

        if (!$status) {
            return redirect()->route('welcome');
        }

        if (!Auth::user()->isFriendsWith($status->user) && Auth::user()->id !==
            $status->user->id) {
            return redirect()->route('welcome');

        }

        $reply = Status::create([
            'body' => $request->input("reply-{$statusId}"),
        ])->user()->associate(Auth::user());

        $status->replies()->save($reply);

        return redirect()->back();
    }

    public function getLike($statusId)
    {
        $status = Status::find($statusId);

        if (!$status) {
            return redirect()->route('welcome');
        }

        if (!Auth::user()->isFriendsWith($status->user)) {
            return redirect()->route('welcome');
        }

        if (Auth::user()->hasLikedStatus($status)) {
            return redirect()->back();
        }

        $like = $status->likes()->create([]);
        Auth::user()->likes()->save($like);

        return redirect()->back();
    }
}

person Luke Vaughan    schedule 16.01.2016    source источник


Ответы (1)


Удалите выражение use для Status в вашем Users.php. Когда вы это делаете, вы фактически пытаетесь использовать \Status. Ваш файл уже находится в пространстве имен SCM, поэтому вам не нужен оператор use для использования классов в том же пространстве имен.

Итак, в определении вашего метода вы говорите, что хотите использовать экземпляр \Status в качестве параметра, но передаете SCM\Status.

person Padarom    schedule 17.01.2016