Call to a member function save() on null laravel - php

Hello guys I'm using laravel 5 polymorphic relation to save the data in the database but I'm facing some problem. When ever I try to save the data in the database it is throwing me this error
Call to a member function save() on null
I don't know why I'm facing this error. I'm following this tutorial fot the polymorphic relation Creating Polymorphic Relations in Laravel 5.
I 'm making a polymorphic relation like this. A post and comment can have many likes.
The like Request validates that if I'm sending a id then this request should be entertained otherwise not
Like Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\LikeRequest;
use App\Commands\LikeCommand;
// use App\Commands\ReadLikeCommand;
use App\Http\Controllers\Controller;
use Illuminate\Bus\Dispatcher;
// use App\Transformers\PostTransformer;
use Exception;
// use App\Events\TestEvent;
use App\Exceptions\Custom\NotPermissionException;
use App\Exceptions\Custom\NameNotFound;
class LikeController extends Controller
{
public function likeComment(LikeRequest $data){
try{
$render = $this->dispatch(new LikeCommand("comment" , $data));
}catch(Exception $e){
$e->getMessage();
}
}
public function likePost(LikeRequest $data){
error_log("1");
try{
$render = $this->dispatch(new LikeCommand("post" , $data));
}catch(Exception $e){
error_log("error : ".$e->getMessage());
}
}
}
Like Command
<?php
namespace App\Commands;
use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Repositories\LikeRepository;
use Exception;
use DB;
use App\LikeModel;
use Artisan;
use App\Repositories\PostRepository;
class LikeCommand extends Command implements SelfHandling
{
use DispatchesJobs;
private $postId;
private $action;
private $data;
/**
* Create a new command instance.
*
* #param $request
*
* #internal param $email
* #internal param $phone
* #internal param $comments
* #internal param $name
*/
public function __construct($action,$request)
{
$this->action = $action;
$this->postId = $request->id;
$this->data = $request;
error_log("Hello in the construct");
}
/**
* Execute the command.
*
* #param TestRepository $TestRepository
*/
public function handle(LikeRepository $LikeRepo, PostRepository $postRepo )
{
error_log("Hello");
error_log("A : ".$this->action );
error_log("ID : ".$this->postId);
if($this->action =="comment"){
error_log("in like comment");
return $LikeRepo->LikeComment( $this->postId);
}else if ($this->action == "post"){
error_log("2");
return $LikeRepo->LikePost( $this->postId, $postRepo , );
}
}
}
Like Repo
<?php
namespace App\Repositories;
use App\Repositories\CommentRepository;
use App\Repositories\PostRepository;
use App\CommentModel;
use App\LikeModel;
class LikeRepository
{
public function create($comment)
{
// error_log("Trying to save now. Let's see");
$Like = new LikeModel;
$Like->post_id = $comment;
// $Comment->post_id = $this->post_id;
$comment->save();
}
public function LikeComment($id) {
// return CommentModel::where('post_id' , $id)->get();
// return CommentModel::get();
}
public function LikePost($id, PostRepository $postRepo){
error_log("3");
$result = $postRepo->getById($id);
error_log("4");
// $Like = DB::transaction(function () use ($LikeRepository) {
$Like = new likeModel;
error_log("5");
$result->Like->save($like);
error_log("6");
$Like->status="success";
// });
return $Like;
}
}
Like Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LikeModel extends Model
{
public $table = "likes";
//
public function likeable()
{
return $this->morphTo();
}
}
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PostModel extends Model
{
//
public $table = "posts";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CommentModel extends Model
{
//
public $table = "comments";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Update
I solved this problem by changing $result->Like->save($like); to this $result->likes->save($like); and int he PostModel I had to change App\Likes to App\LikeModel similarly in CommentModel but now it's throwing me this error error : Method save does not exist.

Your problem in updated version was getting collection of likes but not relation which you need to run $relation->save($like).
See updated code below:
public function LikePost($id, PostRepository $postRepo){
$result = $postRepo->getById($id);
$Like = new likeModel;
error_log("5");
$result->likes()->save($Like);
error_log("6");
$Like->status="success";
return $Like;
}

Related

Getting no result from table , while fetching data using laravel model

I am trying to execute simple CRUD operation using laravel. but it gives an error code 500 , when I try to fetch data from table either by laravel framework as well as with plain PHP.
Here is my controller class.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = DB::select('select * from book');
$data = BookModel::all();
echo($data);
return compact('data');
}
}
axiom , which is been used. ---> "https://unpkg.com/axios/dist/axios.min.js"
Model Class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BookModel extends Model {
protected $table = "book";
public $timestamps = false;
}
It is returning no result from the table.
It worked after I changed my controller to
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return $data;
}
}
But it was giving null result when I was doing something like below
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return view('admin')->withTasks($data);
}
}
Can someone explain why it was not working earlier?
Anyways , Thanks everyone for your help.
Cheeeeeeeeerrsssss!!!!!!!
You need to add response() to return data without view.
Like below the code returns the JSON data from your BookModel that sometimes we need through the ajax request like axios.
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return response()->toJson($data);
}
}
With view you can do the following:
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return view('admin', compact('data'));
}
}
Where you can access the BookModel data through $data variable in your admin.blade.php

Accessing method in another namespace

I'm trying to, from my controller, access a method in a model that is in another namespace and the only way I could do this was to make the method static. Is this the right way to do it, or is there any neater approach?
PagesController.php (controller):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\ConnectedHost;
class PagesController extends Controller
{
/*
* REMOVED CODE HERE FOR READABILITY
* Below is where I instantiate the "connectedHost"-object
*/
$hosts[$hostKey] = new ConnectedHost($hostAttributes['ipv4'], $hostAttributes['mac']);
}
/* REMOVED CODE HERE FOR READABILITY AS WELL */
ConnectedHost.php (helper-file):
namespace App\Helpers;
class ConnectedHost
{
public $ipv4, $mac;
public function __construct($ipv4, $mac)
{
$this->ipv4 = $ipv4;
$this->mac = $mac;
// This is where I call the getName-function staticly,
$this->name = \App\Host::getName();
}
}
Host.php (model):
namespace App;
use Illuminate\Database\Eloquent\Model;
class Host extends Model
{
// The method below is declared static
public static function getName()
{
$name = 'wenzzzel';
return $name;
}
}
If you are directly accessing the method from model like
$data = \App\ModelName::methodName();
Then your method should be static.
if your method is not static you can access like,
$model = new \App\ModelName();
$data = $model->methodName();

RelationNotFoundException Call to undefined relationship Laravel

Why i am getting error for Laravel relationship. I am trying to print_r the values with this relationship. is there any way to get rid of this error?
Controller: this is cart page functions
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('product_tbls')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}
Products_model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product_models extends Model
{
protected $table = "product_tbls";
public function shop_product_all()
{
return $this->hasMany('App\cartmodel');
}
}
Cart model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class cartmodel extends Model
{
protected $table = "shoppingcart";
public function shopcart_product()
{
return $this->belongsTo('App\product_models');
}
}
You're calling a relationship which isn't defined. I think you're passing table name in with which should be relationship function as vivek_23 mentioned in comment. So try the below code:
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('shopcart_product')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}
After fixing with('shopcart_product'), I just append product_id in model like,
public function shopcart_product()
{
return $this->belongsTo('App\product_models', 'product_id);
}
Now getting values from product_tbls

`Class not found` error even though class is defined as a modal

I have the following method in my controller:
public function store(Request $request){
$data = session()->get('dmca');
// return $data;
$notice = Notice::open($date);
$notice->useTemplate($request->input('template'));
$notice->save();
return Notice::first();
}
When the controller runs i get the following error:
Now i do have the following modal class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notice extends Model {
protected $fillable = [
'provider_id',
'infringing_title',
'infringing_link',
'original_link',
'original_description',
'template',
'content_removed'
];
public static function open(array $attributes) {
return new static($attributes);
}
public function useTemplate($template) {
$this->template = $template;
}
}
Now why am i getting this error in laravel class not found , even though i have this class defined ??
Just use use keyword at the top of your controller class.
<?php
namespace App\Http\Controllers;
use App\Notice; // <------------------ use here
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
$data = session()->get('dmca');
// return $data;
$notice = Notice::open($date);
$notice->useTemplate($request->input('template'));
$notice->save();
return Notice::first();
}
}
The use keyword helps php to recognize the class Notice within a certain namespace
Hope this helps!
Add this line to the top of a controller:
use App\Notice;
Or use full namespace:
$notice = \App\Notice::open($date);

How to call function from another class Laravel

I have payroll PayrollProcessController and PayrollHelper class in my Helpers folder.
here's my PayrollProcessController code :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Base\MasterController;
use App\Http\Requests;
use App\Models\PayrollPeriod;
use App\Helpers\PayrollHelper;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Yajra\Datatables\Datatables;
class PayrollProcessController extends MasterController
{
protected $indexView = 'payroll_process.index';
protected $detailView = 'payroll_process.detail';
protected $routeBindModel = 'payroll_process';
protected $redirectPageWhenFormSuccess = 'payroll_process.index'; //Route Name
protected $title = 'Payroll Process';
public function render(View $view, $route = null, $obj = null, $method = 'POST')
{
$payrollPeriodName = PayrollPeriod::pluck('name','id');
$view->with(compact('payrollPeriodName'));
return parent::render($view, $route, $obj, $method);
}
}
and here's my PayrollHelper Code :
<?php
namespace App\Helpers;
use App\Helpers\Exceptions\ValidationException;
use App\Helpers\GeneralHelper;
use App\Models\Config;
use App\Models\Driver;
use App\Models\DriverPayable;
use App\Models\PayrollPeriod;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
final class PayrollHelper {
public static function processPayroll(PayrollPeriod $payrollPeriod)
{
try {
$drivers = Driver::where('active', true)->get();
foreach ($drivers as $driver) {
$payable = new DriverPayable;
$payable->payrollPeriod()->associate($payrollPeriod);
$payable->driver()->associate($driver);
if (!$payable->save()) {
throw new ValidationException($payable->errors());
}
}
} catch (Exception $e) {
Log::error($e);
SessionHelper::setMessage('Unable to process payroll, Please contact system Administrator');
} catch (ValidationException $e) {
Log::info($e->errors);
SessionHelper::setMessage($e->errors);
}
}
}
?>
how to call the processPayroll function ?
Any help will be appreciated
Try this..
Use helper in your controller
use App\Helpers\PayrollHelper;
This is your controller constructor
public function __construct(PayrollHelper $payroll_helper)
{
parent::__construct();
$this->payroll_helper = $payroll_helper;
}
Call method like this
$this->payroll_helper->processPayroll();
Updated
Your controller look like this
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Base\MasterController;
use App\Http\Requests;
use App\Models\PayrollPeriod;
use App\Helpers\PayrollHelper;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Yajra\Datatables\Datatables;
class PayrollProcessController extends MasterController
{
protected $indexView = 'payroll_process.index';
protected $detailView = 'payroll_process.detail';
protected $routeBindModel = 'payroll_process';
protected $redirectPageWhenFormSuccess = 'payroll_process.index'; //Route Name
protected $title = 'Payroll Process';
public function __construct(PayrollHelper $payroll_helper)
{
parent::__construct();
$this->payroll_helper = $payroll_helper;
}
public function render(View $view, $route = null, $obj = null, $method = 'POST')
{
$payrollPeriodName = PayrollPeriod::pluck('name','id');
$view->with(compact('payrollPeriodName'));
//Use where you want
$this->payroll_helper->processPayroll();
return parent::render($view, $route, $obj, $method);
}
}
I just want to share what I have done,
Don't know yet the side effects of this but we'll,
Use helper in your controller
use App\Helpers\PayrollHelper;
And inside the function that is good to consume one of the functions inside Payroll helper, do
$payrollhelper = new PayrollHelper();
Then call any function within the helper doing
$payrollhelper->funtion_name()...
This worked for me
Here is the example how you can apply your class in that way
Import the controller class
use App\Http\Controllers\CategoryController;
Create an instance of this class
$category_instance = new CategoryController();
Call the method
$category_instance->convert_json_serial_numbers_to_arrays($serial_number);

Categories