I come to you today because I don't really understand where my problem is coming from. When I try to pass a dynamic argument in my url, I systematically fall on a 404 page. I looked in my db, there is the article, I looked in my model, it points well to this table of the db, I looked at my controller, I specify this article well... I do not understand too much.
My web.php:
Route::get('/article/{article}', 'ArticleController#index');
My controller:
class ArticleController extends Controller
{
public function index($article)
{
$scopedArticle = Article::where('id', $article)->firstOrFail();
return view('article', compact('scopedArticle'));
}
}
My model:
class Article extends Model
{
protected $table = 'articles';
protected $fillable = [
'titre', 'image', 'description',
];
}
My database:
So I don't really understand...
With route model binding there is no need to add $scopedArticle = Article::where('id', $article)->firstOrFail();
Example usage:
goto http://yourstie.com/article/1
class ArticleController extends Controller
{
public function index(Article $article)
{
return view('article', compact('article'));
}
}
Related
I have a pivot table post_profile that contains the hearts (likes) of each post.
Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function profilesHearted()
{
return $this->belongsToMany(Profile::class);
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage()
{
$imagePath = ($this->image) ? $this->image : 'profile/czyhBQu2YWX6gvBivZrnEs2ORoBwr3d9mzkwxk8k.png';
return $imagePath;
}
public function followers()
{
return $this->belongsToMany(User::class);
}
public function heartedPosts()
{
return $this->belongsToMany(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
The main view which shows all posts of followed users is working along with the heart button but underneath I want to show liked by <x> and 30 others, where x is first follower of the user if any of the user's follower hearted the post. I tried many ways to get x but I am a bit lost.
This is PostsController.php index function which leads to the view:
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts', 'users' ));
}
What I tried to do but deleted eventually after failing is get each post in foreach loop and check if each $post->heartedProfiles(contains($users)), but this doesn't work this way. So another way I tried is in my view ie, index.blade.php
#foreach($users as $userid)
User::select('id')->where('profile_id', $userid)->first()
->profile->profilesHearted->find($post->id)
#endforeach
Which doesn't work because User class cannot be used directly in view without passing.
I'm sure there is a simple and cleaner way to do this in Laravel. This is my first time using Laravel and ORM programming so really felt lost. Took the FreeCodeCamp Instagram clone tutorial and understood the basics. All I need is to give me some idea to get started.
When dealing with many to many you need to use the pivot functions, so you would do like so
Post::profilesHearted()->wherePivotIn('profile_id', $users)->first()
Not checked the code but hopefully it will give you the idea.
I get this error message if I try to run my post on postman:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::posts()
My routes Looks like this:
Route::middleware('auth:api')->group(function ()
{
Route::get('posts', ['as' => 'posts', 'uses' => 'Api\PostController#index']);
}
And the Controller like this:
class PostController extends Controller
{
public function index()
{
$posts = Auth::client()->posts()->get();
dd($posts);
return response()->json(['data' => $posts], 200, [], JSON_NUMERIC_CHECK);
}
}
My Client model:
class Client extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, HasApiTokens, Notifiable;
protected $table = 'clients';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function posts()
{
return $this->hasMany(Post::class);
}
}
And my Post model:
namespace App;
use App\Client;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function client()
{
return $this->belongsTo(Client::class);
}
}
If I dump this: $posts = Auth::user()->get();
I get an Output, but I want to get the post Output.
You should define the relationship first.
<?php
...
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
Once it has been defined, you can access the collection of posts by accessing the posts property. Most important, you should retrieve a single row firstly, then access the collection of posts like this:
$client = Client::find(1);
$posts = $client->posts;
Or you can serve the relationship as query builders like this:
$posts = App\Client::find(1)->posts()->where('name', 'tests')->get();
Iff it still occur the error, You should check if Auth::client()return client model instance.
dd(Auth::Client());
I'm not sure how you've defined Auth::client(), but judging by some of the code there is a misconception of how models are instantiated, and what get() does.
get() returns a collection of results.
Auth::user() already returns a user instance, when you call Auth::user()->get(), you are sending a second query to the database and returning a list of users.
$user->posts()->get() has a more conventional/memoized way of accessing the dataset, `$user->posts.
I'd recommend checking out your Auth::client() method and make sure you're not accidentally returning a new query.
Hello I´m writing an API and I want to display more information about the related model.
Routes.php
Route::resource('makes', 'MakesController');
MakesController.php
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->json($data);
}
}
This returns only information about the makes (id, name)
but how can I display also how many models has each make?
I have defined these two models
class Make extends Model
{
public function models()
{
return $this->hasMany('App\CarModel');
}
}
class CarModel extends Model
{
public function make()
{
return $this->belongsTo('App\Make');
}
}
You can define $visible field in the Make model's class like this:
protected $visible = ['models'];
This will automatically appends the related model's array to array/json.
You can also use an optional way with makeVisible method:
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->makeVisible('models')->json($data);
}
}
I am creating a website using laravel. I have a small issue with eager loading. I have already made several websites with laravel, but still I can't find what is wrong here.
This is my config model:
<?php
class Config extends \Eloquent {
protected $table = "configs";
public function groups() {
return $this->hasMany('ConfigOptionGroup', 'config_id');
}
}
And this is my testcontroller class:
<?php
namespace WebsiteController;
class DemoController extends \BaseController {
public function getTest() {
$c = \Config::where('id', 1)->with(['groups' => function($q){
$q->whereNull('config_option_group_id');
}])->first();
return $c;
}
}
Whenever I surf to the url that calls the getTest method I get an error saying Call to undefined method Illuminate\Database\Query\Builder::groups(). However, the function groups() exists in the Config model.
When I remove the with() function from the query, it works just fine. But I can never load the groups via the relation.
Is there anyone who can help me with this problem?
Update: I have removed the Config facade by commenting out the line in /app/config/app.php.
Im trying to add a comment system to my laravel app.
But I can't seem to get it working.
I have two models
class Post extends \Eloquent {
protected $table = 'posts';
public function comments()
{
return $this->hasMany('Comment','postId');
}
}
and my Comment model
class Comment extends \Eloquent {
protected $table = 'comments';
public function post()
{
return $this->belongsTo('Post');
}
}
in my DashBoardController I'm trying to get the output from the models
use App\Models\Post;
use App\Models\Comment;
use Input, Redirect, Sentry, Str, View, Notification;
class DashboardController extends \BaseController {
public function index()
{
$post = Post::find(3)->comments()->comment;
print_r($post);die;
}
}
I think my database is properly linked, but now I'm getting the error
'Class Comment not found'.
Any advice on this one?
First try this: composer dump-auto (as commented by user1669496)
if this didn't helped then change your model...
Change this:
return $this->belongsTo('Post');
to smth like this:
$this->belongsTo('App\Models\Post');
Do the similar for Post model.
Just change App\Models\XXXX to your namespace where you have Post model saved.
I had similar problem and this helped me, hope it will help you.