Laravel BadMethodCallExeption Query Builder post - php

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.

Related

get data from model with condition laravel 5.7

I have Users_group model in my Laravel project.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function getGroupData()
{
return $this->hasOne('App\Group','id','group_id');
}
}
And when I want to get data from this model I use this my custom method:
$data = App\Users_group ::get();
It's working great
I want to get the data from model with condition not like this:
$data = App\Users_group::where('group_id','>',5)->get();
I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.
Thanks!
You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.
In your case, you could add the following boot method to your model:
protected static function boot()
{
parent::boot();
static::addGlobalScope('groupOver5', function (Builder $builder) {
$builder->where('group_id', '>', 5);
});
}
try this one in by using scope in model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function scopeGetGroupData($query,$value,$opertor = '>')
{
return $query->where('group_id', $opertor, $value);
}
}
get data in controller like this u can pass also parameter in method
App\Users_group::GetGroupData($value)->get();

Paginate data from relationship model in Laravel

Apologies if the title doesn't completely make sense... I wasn't sure if the exact terminology for the linking of models are the associated data in their controllers.
I'm trying to paginate a table with the posts created by a user.
I managed to paginate it previously, without the user_id in the posts table. But I've added the user_id to the posts table, and run the migration which works fine.
The following is my Post model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
And this is my User model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password',];
protected $hidden = ['password', 'remember_token',];
public function posts() {
return $this->hasMany('App\Post');
}
}
And this is the relevant section of the post controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Session;
use Carbon\Carbon;
class PostController extends Controller
{
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('posts.index')->with('posts', $user->posts);
}
I thought that it would simply be a case of appending ->paginate(5) to the $user in the PostController, but that doesn't appear to work.
I get the following:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I've tried including the {!! $posts->links() !!} in the posts.index view before the #foreach but that gives:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I'm trying to learn Laravel basics by creating this crud application, and have tried combining two tutorials together, but I'm clearly missing something.
You can call ->paginate() on the relationship like this (also I've removed the unnecessary user query, since auth()->user() will execute it already):
public function index()
{
$user = auth()->user();
$posts = $user->posts()->paginate();
// Or with 1 line: $posts = auth()->user()->posts()->paginate();
return view('posts.index')->with('posts', $posts);
}

Laravel Destroy() is not removing any record from DB

Database Image
This is my controller's index method. When i run the code it does nothing.
public function index()
{
Customer::destroy(1);
return view('customer');
}
Model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model {
protected $guarded = [];
public $timestamps=false;
}
Try using delete instead of destroy like this:
Customer::findOrFail(1)->delete();
or you can try directly from database using eloquent query builder:
Customer::where('id', 1)->delete();
You can also write your code like this
public function getDeleteTag($id)
{
DB::table('tags')
->where('id','=',$id)
->delete();
return Response::json(['message' => 'Tag has been deleted successfully!']);
}

How do I access the attributes of a related model via method chaining

I have the following models, Item.php and Shipment.php set up. What I am trying to do is display the Item names, based on the shipment ID. I can access the shipments via $shipments = App\Shipment::where('id',4)->get(); but I am totally lost as to how to retrieve the item names, based on the Shipment model.
I am thinking something along the lines of $shipment->items()->getName or the like, but I cannot seem to wrap my head around it.
Item.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $fillable = ['name',
'description',
'category',
'condition'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function category() {
return $this->hasOne('App\Category');
}
public function shipments(){
return $this->belongsToMany('App\Shipment');
}
Shipment.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Shipment extends Model {
protected $fillable = ['id',
'item_id',
'qty',
'user_id'
];
public function user(){
return $this->belongsTo('App\User');
}
public function items(){
return $this->hasMany('App\Item','id','item_id');
}
It's important to know what a certain method will return. If it is a collection or a single model instance. This for example returns a collection (even if it only has one model in it)
App\Shipment::where('id',4)->get();
Instead use first() or just find() to add a where clause for the id and then only return one:
App\Shipment::find(4);
With the relationship it's similar. Since items is a hasMany relation, it will always return a collection. That means usually you will retrieve the items and loop over them:
foreach($shipment->items as $item){
echo $item->name;
}
Also note that there's a difference between $shipment->items() and $shipment->items.
For more on that, read this answer.

Posting data return blank with a Laravel controller

I have a problem posting data in Laravel 5. I've done a page that post stuff on a controller that would create a new row on a database, according to Eloquent class. But when I post that, I receive a blank page and nothing works.
This is my controller, focused on the affected class:
<?php namespace App\Http\Controllers;
use App\T_subject;
use App\T_reservation;
use Date;
use Request;
use Config;
use Validator;
use Auth;
class TutoringController extends Controller {
public function reserve(Request $request)
{
$reservation = new T_reservation;
$reservation->user_id = Auth::user()->id;
$reservation->subject_code = $request->input('subject');
$reservation->date = $request->input('date');
$reservation->topic = $request->input('topic');
$reservation->save();
return redirect('/tutoring/view/'.$request->input('subject'));
}
}
This is my Eloquent model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class T_reservation extends Model {
protected $table = 't_reservations';
public function user()
{
return $this->belongsTo('App\User');
}
}
And my routes file:
<?php
Route::post('tutoring/reserve', ['middleware' => 'auth', 'uses' => 'TutoringController#reserve']);
Where's the problem?
In your routes file there is no definied route for your final redirection: '/tutoring/view/'.$request->input('subject').
Also, your model have no fillable property, which should list properties for which you can make a mass assignment. For instance something like this:
protected $fillable = ['user_id', 'subject_code', 'date', 'topic'];

Categories