Laravel call to a member function on null when using assertsee - laravel

So all my other tests are working except this one when I test the view if it has this string or not. Problem is I'm getting an error message that the method being called is on null but is working when I access the page.
Error message:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function getCode() on null
/home/vagrant/Code/team-stores/app/Http/Controllers/StoreManager/OrderTrackingController.php:20
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:55
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:44
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Route.php:203
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Route.php:160
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Router.php:574
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:102
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Router.php:576
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Router.php:535
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Router.php:513
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:174
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:102
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:149
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:116
/home/vagrant/Code/team-stores/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:234
/home/vagrant/Code/team-stores/tests/Feature/OrderTrackingTest.php:152
Test:
public function an_admin_can_view_all_orders_with_their_status()
{
$this->withoutMiddleWare();
StoreSession::setMyStore($this->store->code);
$orders = factory(CompletedOrder::class, 30)->create(['store_id' => $this->store->id]);
foreach ($orders as $order) {
factory(CompletedOrderItem::class, 5)->create(['completed_order_id' => $order->id]);
}
$response = $this->call("GET", route('list_completed_orders'));
foreach ($orders as $order) {
$response->assertSee($order->invoice()->getCode());
}
}
Controller:
public function index()
{
$store = StoreSession::getMyStore();
$completedOrders = CompletedOrder::where('store_id', $store->getId() )->get();
foreach ($completedOrders as $order) {
Log::info($order->invoice()->getCode());
}
return view('store-manager.order-tracking.index', compact('store', 'completedOrders'));
}
Thanks in advance.

Related

how i avoid this error Trying to get property 'id' of non-object?

i have this index function to show just my hotels :
public function index()
{
$myhotels = hotel::where('created_by',Auth::user()->id)->first();
$reservations = Reservation::where('hotel_id',$myhotels->id)->get();
return view('moderateur/reservation',compact('reservations'));
}
but when there is no hotel i got this error Trying to get property 'id' of non-object
itry this but still the same
public function index()
{
$myhotels = hotel::where('created_by',Auth::user()->id)->first();
if (!hotel::where('created_by',Auth::user()->id)->exists()){
$reservations = Reservation::where('hotel_id',$myhotels->id)->get();
return view('moderateur/reservation',compact('reservations'));
}
return view('moderateur/reservation');
}
how can i fix this :( ? and when there is no hotels i want to be shown 'no hotels'
Check if the object is empty before executing the rest of your code or you firstOrFail().
eg.
public function index()
{
...
if (!empty($myhotels) {
...
return view('moderateur/reservation');
}
}
You need to check if the hotel exists:
public function index()
{
$myhotels = hotel::where('created_by', Auth::user()->id)->first();
if ($myhotels) {
$reservations = Reservation::where('hotel_id', $myhotels->id)->get();
return view('moderateur/reservation', compact('reservations'));
}
return view('moderateur/reservation');
}
While you first tried to fetch the hotel, then you were checking if the hotel doesn't exist. Since it doesn't exist, you were entering the if statement.
And then in the view:
#if ($reservations)
show reservation details
#else
show that the reservaiton is not found
#endif
https://laravel.com/docs/7.x/blade#if-statements

How to remove or unfriend through API

This is database structure
This is API
Route::post('/friend', 'FriendController#index');
Route::post('/removerequest/{id}', 'FriendController#removerequest');
This is controller code which into friend request method and remove method, but error in remove friend method..
public function index(Request $request) {
$sender = Friend::where('sender_id', $request->sender_id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->sender_id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
return response()->json($response);
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
return response()->json($response);
}
}
public function removerequest($id){
$friends = Friend::all()
->where('receiver_id')
->where('sender_id')
->approved('accept')
->delete();
}
Error is
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::approved does not exist. in file /home/ynvih0l26evc/public_html/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 104
enter code here
Update your Route to
Route::delete('/removerequest/{id}', 'FriendController#removerequest');
//change
->approve('approved', 'accept')
to
->where('approved', 'accept')
Update your controller method to
public function removerequest($id){
$friends = Friend::Find($id)->delete(); //see update here
//->where('receiver_id')
//->where('sender_id')
//->where('approved', 'accept')
//->delete();
}
OR
public function removerequest($id){
Friend::where( ['id' => $id, 'approved' => 'accept'])->delete();
}

Laravel ORM relationship returns error when value not present in DB

I have an issue with querying relationships.
I am querying relations between Projects, Companies and Products. However, whenever a Project ID is not present in the database an fatal exception is trown:
Call to a member function companies() on a non-object
public function index($i) {
return $this->returnTop($i, Array(
'projectid' => 5,
'products' => Array(1, 2, 3)
)
);
}
public function returnTop($count = 6, $args = Array()) {
$companies = Project::find($args['projectid'])->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
}
Now, I know that project id 5 is not present in the DB, and this is likely to be the cause of this error, but I want to return a message instead of the application throwing a fatal error....
Any ideas?
Just check if find() returns null. Something like this:
$project = Project::find($args['projectid']);
if(is_null($project)){
return Response::json(['message' => 'Project not found']);
}
$companies = $project->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
An alternative would be findOrFail which throws a ModelNotFoundException. You could handle the exception globally or catch it inside the controller:
try {
$companies = Project::findOrFail($args['projectid'])->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
return Response::json(['message' => 'Project not found']);
}
You first have to test whether the returned object is actually not null. Blindly assuming a database query succeeds is waiting for sh*t to hit the fan.
public function returnTop($count = 6, $args = Array()) {
$project = Project::find($args['projectid']);
if($project) {
$companies = $project->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
}
else {
return; // .. your error or whatever
}
}
Also the "call to a member function on a non-object" is quite specific, it tells you that a method (member function) could not be called due to the fact that you are trying to call it on a non-object.

Laravel Model to View - Undefined variable

I'm sure I'm missing something blindingly obvious but cannot see to get the division name to appear on my view.
It keeps returning Undefined variable: division_name
DIVISON.PHP (Model)
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
public function scopeGetDivisionName($query, $slug)
{
return $query->select('division_name')
->join('division_industry_job', 'division_industry_job.division_id', '=', 'divisions.id')
->join('industryjobs', 'division_industry_job.industry_job_id', '=', 'industryjobs.id')
->where('industryjobs.slug', '=', $slug);
}
}
JOBCONTROLLER.PHP (Controller)
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job')->with('job', $job, $division_name);
}
JOB.BLADE.PHP (View)
{{$division_name->division_name}}
{{$job->job_title}}
You're not passing the variable to your view properly.
// This won't work
return View::make('job')->with('job', $job, $division_name);
It should be
return View::make('job')->with('job', $job)
->with('division_name', $division_name);
Or
return View::make('job', array(
'job' => $job,
'division_name' => $division_name
));
You can use also the compact method for passing variables to your view :
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job', compact('job', 'division_name'));
}

Magento Fatal error: Call to a member function setCurPage() on a non-object

I created a block with a toolbar, but an error happened:
Fatal error: Call to a member function setCurPage() on a non-object
I did quite some search-queries but can’t find the solution.
Is there someone who knows the reason?
Please see my code below:
class test_Promotion_Block_List extends Mage_Catalog_Block_Product_List {
public function __construct() {
parent::__construct();
$collection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array('finset' => '98'))
->addAttributeToSort('created_At', 'desc')
;
$this->setCollection($collection);
}
protected function _prepareLayout() {
parent::_prepareLayout();
$toolbar = $this->getToolbarBlock();
// called prepare sortable parameters
$collection = $this->getCollection();
// use sortable parameters
if ($orders = $this->getAvailableOrders()) {
$toolbar->setAvailableOrders($orders);
}
if ($sort = $this->getSortBy()) {
$toolbar->setDefaultOrder($sort);
}
if ($dir = $this->getDefaultDirection()) {
$toolbar->setDefaultDirection($dir);
}
$toolbar->setCollection($collection);
$this->setChild('toolbar', $toolbar);
$this->getCollection()->load();
return $this;
}
public function getDefaultDirection() {
return 'asc';
}
public function getAvailableOrders() {
return array('name' => 'Name', 'position' => 'Position', 'children_count' => 'Sub Category Count');
}
public function getSortBy() {
return 'name';
}
public function getToolbarBlock() {
$block = $this->getLayout()->createBlock('testpromotion/toolbar', microtime());
return $block;
}
public function getMode() {
return $this->getChild('toolbar')->getCurrentMode();
}
public function getToolbarHtml() {
return $this->getChildHtml('toolbar');
}
}
Error sniffing:
Magento Product_List blocks are "pagination aware". They take URL paging parameters and apply it to the collection of products to be displayed.
That means that the error you're seeing occurs somewhere in the parent classes of your block. That method is called for collections so it means that the result of one of the selects is not an object but either an array or null.
It's more likely you're receiving an array response but you didn't initialize the collection with the response so calling the method on an array triggers this error.
Error info:
Please specify the full error info including file and line where it occurs. This will help find the source of the error.
Also use the following line next to (before / after any operation that might change the $collection variable) because you may be calling $this->setCollection(null).
var_dump(is_object($collection) ? get_class($collection) : get_type($collection));

Resources