M.Milton M.Milton - 5 months ago 13
PHP Question

Laravel: FatalErrorException

I have problem with like system. If i click on like button it throws me an error:
FatalErrorException in PostController.php line 80:

Class 'App\Http\Controllers\Like' not found


Line 80 in my post Controller is:

$like = new Like();


This is my full function:

public function postLikePost(Request $request){
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true : false;
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();

$like = $user->likes()->where('post_id', $post_id)->first();
if($like){
$already_like = $like->like;
$update = true;
if($already_like == $is_like){
$like->delete();
return null;
}
} else{
$like = new Like();
}
$like->like = $is_like;
$like->user_id = $user->id;
$like->post_id = $post->id;


if($update){
$like->update();
}else{
$like->save();
}
return null;
}


Do you know where is the problem? Thank you.
(I am using Laravel v5.2.39)

Answer

You need to write use Your_Namespace\Like; before class statement.

In controller:-

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use DB;

use App\Like; // use Your_Namespace\Like; add this line here

OR you can directly write,

$like = new \App\Like(); // new \Your_Namespace\Like();

Please refer documentation.

By default Your_Namespace is App.

You can change namespace by below command:-

php artisan app:name Your_Namespace