Laravel 5.1 Call to undefined method Illuminate\Database\Query\Builder::cartItems() - php

I have the following model and controller but it keeps throwing error:
Call to undefined method Illuminate\Database\Query\Builder::cartItems()
This is my model and controller:
class Cart extends Model
{
protected $fillable = [
'user_id',
'coupon_id',
];
public function cartItems()
{
return $this->hasMany('App\CartItem');
}
}
use App\Cart;
use App\CartItem;
class CartController extends Controller
{
public function index()
{
$userId = Auth::user()->id;
$cart = Cart::where('user_id', '=', $userId);
$cartItems = $cart->cartItems()->get();
//...some other stuff...
return view('cart.index', compact('cartItems'));
}
}

Don't call it as a function:
$cart = Cart::where('user_id', '=', $userId)->first();
$cartItems = $cart->cartItems;
Laravel will take care of the rest, and get the items from the database.

Related

PHP Laravel save() is not updating record

I am a beginner in laravel. I was updating records but I can't figure out what is wrong with my $student->save();
My controller code is as follows
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
use PHPUnit\Framework\MockObject\Builder\Stub;
class HomeController extends Controller
{
public function read() {
$students = Student::all();
return view('read',['Students'=>$students]);
}
public function insert() {
return view('insert');
}
public function insertPost(Request $req) {
$student=new Student();
$student->Name = $req->input('name');
$student->Marks = $req->input('marks');
$student->save();
return redirect('/');
}
public function update($id) {
$student = Student::find($id);
return view('update',['Student'=>$student]);
}
public function delete($id) {
$student = Student::find($id);
$student->delete();
}
public function updatePost(Request $req) {
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
// Student::where('ID',$req->input('id'))
// ->update(['Name'=>$req->input('name'),
// 'Marks'=>$req->input('marks')]);
return redirect('/');
}
}
The Main main in updatePost(); is causing the records not updating
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
I changed the way of updating records to
Student::where('ID',$req->input('id'))
->update(['Name'=>$req->input('name'),
'Marks'=>$req->input('marks')]);
and it worked. But I wanted to know at which part I was making mistake in it.
You need to set your primary key to 'ID'
By default the primary key or PK name is 'id'
But in your code it changed to 'ID'
So you need to go to your User.php model class
and add this line
public $primaryKey = 'ID';
One thing you can try is using Laravel's update method. update will handle the save internally.
$student = Student::findOrFail($req->input('id')));
$student->update([
'Name' => $req->input('name'),
'Marks' => $req->input('marks'),
]);

How can I pass a parameter from the controller index function to the model's functions? LARAVEL

//------------------------------//
//below is the controller index function code //
//------------------------------//
public function index($from, $to,$id)
{
$data=Attendance::where('attendance_date','>=',$from)
->where('attendance_date','<=',$to)
->with('userAttendance')//--> **I need to pass the $id to this function in the model**
->with('admin')
->get()
//---------------------------------//
//below is the model code //
//----------------------------------//
class Attendance extends Model
{
protected $table = "attendances";
protected $fillable=[
'attendance_date',
'admin_id',
];
//---> **i need the $id passed to here**
public function userAttendance()
{
return $this->belongsToMany('App\User', 'user_attendances','attendance_id','user_id')
->withPivot(
'present_absent',
'excuse',
'attendance_key_amount',
'verified_date',
'comment',
);
}
}
just try this
Controller:
public function index()
{
$id = 50;
Product::getId(50);
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public static function getId($id){
dd($id);
}
}

Laravel Eloquent persist 1:n

I want to create a laravel crud repository for a model. The model has 1 1:n and 1 n:n relationship.
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'description', 'merchantId', 'name', 'link', 'pictureUrl', 'ean', 'brand', 'aktPrice', 'affiliatePortal', 'programId'
];
public function prices() {
return $this->hasMany(Price::class);
}
public function categories() {
return $this->hasMany(Categorie::class);
}
}
Now I want to create a repository which has a save method and a controller for a restapi, which calls the save methode. My question is how should a save method looks that the entity is saved correctly and which mapping operations have to be done before that it works. I hope someone can help me and send me a save method, or a crud repository for my case and can help me to design the controller.
A Controller, with all the crud operations, look like this:
<?php
namespace App\Http\Controllers;
use App\Models\Room;
use Illuminate\Http\Request;
class RoomController extends Controller
{
public function index()
{
$rooms = Room::all()->toArray();
return $rooms;
}
public function add(Request $request)
{
$room = new Room;
$room->create($request->all());
return response()->json('The room successfully added');
}
public function getById($id)
{
$room = Room::find($id);
return response()->json($room);
}
public function update($id, Request $request)
{
$room = Room::find($id);
$room->update($request->all());
return response()->json('The room successfully updated');
}
public function delete($id)
{
$room = Room::find($id);
$room->delete();
return response()->json('The room successfully deleted');
}
}

Filtering data with spatie query builder using trait

I put logic from my function index() of UserController in trait taht i created:
public function index()
{
$this->authorize('view', Auth::user());
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return UserResource::collection($users);
}
and this is my trait :
<?php
namespace App\Http\Traits;
use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;
trait Filterable
{
public function filter()
{
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return $users;
}
}
So now my function index() looks like this:
use Filterable;
public function index()
{
$this->authorize('view', Auth::user());
$users = $this->filter();
return UserResource::collection($users);
Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters
Custom filters
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class FiltersUserPermission implements Filter
{
public function __invoke(Builder $query, $value, string $property) : Builder
{
return $query->whereHas('permissions', function (Builder $query) use ($value) {
$query->where('name', $value);
});
}
}
use Spatie\QueryBuilder\Filter;
// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
->get();
// $users will contain all users that have the `createPosts` permission

Call to undefined relationship [user_id] on model [App\User]

I'm trying Laravel 5.4 (i usually work with 5.1) and im actually copypasting most of the code, so i dont understand what is the trouble, maybe is because there is a better way to do it but yeah, its been 1 hour and i cant get past this;
Hope you can help me with this..
In case this isn't enough i'll be posting my views and routes. Thank to everyone.
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['user_id', 'user_name', 'user_birthday'];
public static $rules = [
'user_name' => 'required|max:255',
'user_birthday' => 'required'
];
public $timestamps = false;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
public function index()
{
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
return view('admin.users.index')->with("user", $users);
}
public function create()
{
return view('admin.users.create');
}
public function store(Request $request)
{
$users = new User($request->all());
$users->save();
return redirect()->route('admin.users.index');
}
public function show($id)
{
$users = User::find($id);
}
public function edit($id)
{
$users = User::find($id);
return view('admin.users.edit')->with('user', $user);
}
public function update(Request $request, $id)
{
$users = User::find($id);
$users->user_name = $request->user_name;
$users->user_birthday = $request->user_birthday;
$users->save();
return redirect()->route('admin.users.index');
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
return redirect()->route('admin.users.index');
}
}
Your error is from the following line of code. When you use with on a model is to load children relationships or sub-models. That is why the application is looking for the relationship user_id in the User Model thinking that it's a sub-model of the User model but it's not, so it return an error.
wrong
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
correct
$users = User::orderBy('user_id', 'ASC')->paginate(10);

Categories