I have a MongoDB connection & MySQL Connection details setup in my config/database.php file. I can connect to the MongoDB Details and get a response but when i try connect to the MySQL database, i get the following error:
FatalThrowableError in Builder.php line 1514:
Call to a member function compileSelect() on null
I've tried the solutions from this page:
Issue with Out of the box Laravel Authentication but none of the solutions have worked.
I'm not using any authentication on the app, just querying a MySQL database to return data.
[Updated]
Route link from app/Http/routes.php
Route::get('v1/{showdata}/{name}', 'ShowDataController#percentData');
Controller: ShowDataController.php
namespace App\Http\Controllers;
use App\ShowData;
use App\MongoDataPull;
class ShowDataController extends BaseController
{
public function percentData($showdata, $name)
{
$showdata;
$name;
$signupsremaining = 0;
//Percentage Calculator
if ((ShowData::where('name', '=', $name)->first()) === null) {
// If not found, change status to Not Listed
$percentagetakeup = 'Not Listed';
} else {
// If found, Run Percentage Calculator
$totalrequired = ShowData::select('total_required')->where('name', '=', $name)->value('total_required');
$currentinterest = ShowData::select('current_interest')->where('name', '=', $name)->value('current_interest');
$percentagetakeup = round((($currentinterest) / $totalrequired) * 100);
// Calcualte the number of signups remaining for the fibrehood.
$signupsremaining = $totalrequired - ($currentinterest);
if ($signupsremaining < 0) {
$signupsremaining = 0;
} else {
$signupsremaining = $signupsremaining;
}
}
return ['percentagetakeup' => $percentagetakeup, 'signupsremaining' => $signupsremaining];
}
}
From ShowData Model ShowData.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ShowData extends Model
{
protected $table='qualify';
protected $fillable=[
'id',
'name',
'total_required',
'current_interest',
'status'
];
}
Related
I am beginner in Laravel 7, I am using two tables 'empmast' and 'empatten'. I displayed the values of empmast (empid, empname) and joined two fields (empstatus, doa) with same. Then I tried to push these values to 'empatten' table. The thing is these values are trying to save in the empmast instaed empatten table. Kindly assist.
Complete Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' in 'field list'
(SQL: insert into `empmast` (`empid`, `empname`, `empstatus`, `doa`, `updated_at`, `created_at`) values (2, Kirupa Shankar, Present, 17-05-2020, 2020-05-17 06:34:26, 2020-05-17 06:34:26))
EmpAttenController:
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request, Empatten $empatten)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}
Empatten(Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Empatten extends Model
{
protected $fillable = [
'empid' => 'array',
'empname' => 'array',
'empstatus' => 'array',
'doa'
];
}
Create new instance of your model before you try to save
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten = new Empatten(); // initiate your model class
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}
So i've modified some code to add a Like function to a table called sources, this sources have the relation "hasMany" with the table likes.
It doesn't work and I don't get any errors, neither Javascript or PHP errors.
When I like the page it seems like the Ajax don't get called because the page reload to /public/view#, so nothing get submitted to the database.
I don't know how to sort this out.
View:
#foreach($post->sources as $source)
<a>{{$source['link']}}</a>
<div class="interaction" data-sourceid=" {{ $source['id'] }} ">
{{ Auth::user()->likes()->where('source_id', $source['id'])->first() ? Auth::user()->likes()->where('source_id', $source['id'])->first()->like == 1 ? 'You like this source' : 'Like' : 'Like' }} |
{{ Auth::user()->likes()->where('source_id', $source['id'])->first() ? Auth::user()->likes()->where('source_id', $source['id'])->first()->like == -1 ? 'You don\'t like this source' : 'Dislike' : 'Dislike' }}
</div>
<br>
#endforeach
<script>
var token = '{{ csrf_token() }}';
var urlLikeSource = '{{ route('likesource') }}';
</script>
app.js:
$('.like-source').on('click', function(event){
event.preventDefault();
sourceId = event.target.parentNode.dataset['sourceid'];
var isLike = event.target.previousElementSibling == null; //Checks if it's a like or dislike.
$.ajax({
method: 'POST',
url: urlLikeSource,
data: {isLike: isLike, souceId: sourceId, _token: token}
})
.done(function(){
//Change the page when .ajax has been executed.
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this source' : 'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this source' : 'Dislike';
//Make sure you can't dislike and like at the same time.
if(isLike){
event.target.nextElementSibling.innerText = 'Dislike';
} else {
event.target.previousElementSibling.innerText = 'Like';
}
});
});
routes:
Route::post('/likesource', [
'uses' => 'SourceController#sourceLikeSource',
'as' => 'likesource'
]);
SourceController.php:
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Post;
use App\Like;
use App\Source;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class SourceController extends Controller{
public function sourceLikeSource(Request $request)
{
$source_id = $request['sourceId'];
$is_like = $request['isLike'] === 'true'; //Get's passed as string in request, changed to boolean.
$update = false;
//REDO WITH SMARTER SOLUTION
if($is_like == 0){
$is_like = -1;
}
$source = Source::find($source_id);
if(!$source){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('source_id', $source_id)->first(); //First has to be specified
if($like){
$already_like = $like->like;
$update = true;
//Deletes if it already exists.
if($already_like == $is_like){
$like->delete();
return null;
}
} else {
$like = new Like(); //Creates new row for Like in table
}
$like->like = $is_like; //Set's whatever $like->like to whatever $request['isLike'] passed.
$like->user_id = $user->id;
$like->source_id = $source_id;
if($update){
$like->update();
}else{
$like->save();
}
return null;
}
}
Like.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function post()
{
return $this->belongsTo('App\Post');
}
public function source()
{
return $this->belongsTo('App\Source');
}
public function comment()
{
return $this->belongsTo('App\Comment');
}
}
Source.php model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Source extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
public function likes()
{
return $this->hasMany('App\Like');
}
}
Edit:
Rookie mistake by me, I cleared the browser cache. The browser used an old app.js file. Now the ajax seemed to get called correctly, however there's still no new rows in the likes table.
Edit 2:
I gave the data within the Ajax call sourceId: 1 and isLike: 2. There were still no new rows being created in the table likes.
So the problem seems to be in the routes, controller or any of the models.
Edit 3:
I changed the route to a route I knew works properly, I added a csfr_token exception to make sure the token wasn't screwing anything up. I made sure everything in the models were right and I finally made sure everything in the controller was being called correctly.
I truly can't find any problem.
The only thing I can think about is that the likes table "belongsTo" a lot of tables. I made the post_id, comment_id and source_id nullable when I created the table migration.
Should I use some other relationship in the models?
I have two following controller declarations in Yii 2. Former gets the id automatically after the save, whereas latter does not.
This one gets the $test->id automatically after $test->save()
namespace app\controllers;
use yii;
use yii\web\Controller;
use app\models\test\Test;
class TestController extends Controller
{
public function actionAdd()
{
$model = new Test;
if ($model->load(Yii::$app->request->post()) && $model->save())
{
var_dump($model);
return 'success';
} else {
return $this->render('add', [
'model' => $model,
]);
}
}
}
Where this one does not
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\customer\Customer;
use app\models\customer\Phone;
use app\models\customer\CustomerRecord;
use app\models\customer\PhoneRecord;
class CustomersController extends Controller
{
private function store (Customer $customer)
{
$customerRecord = new CustomerRecord();
$customerRecord->name = $customer->name;
$customerRecord->birthDate = $customer->birthDate->format('dd-mm-yyyy');
$customerRecord->notes = $customer->notes;
echo 'customer before save';
var_dump($customerRecord);
$customerRecord->save();
echo 'customer after save';
var_dump($customerRecord);
foreach ($customer->phones as $phone)
{
$phoneRecord = new PhoneRecord();
$phoneRecord->number = $phone->number;
$phoneRecord->customer_id = $customerRecord->id;
$phoneRecord->save();
}
}
private function makeCustomer(CustomerRecord $customerRecord,
PhoneRecord $phoneRecord)
{
$name = $customerRecord->name;
$birthDate = new \DateTime($customerRecord->birthDate);
$customer = new Customer ($name, $birthDate);
$customer->notes = $customerRecord->notes;
$customer->phones[] = new Phone($phoneRecord->number);
return $customer;
}
public function actionAdd()
{
$customer = new CustomerRecord;
$phone = new PhoneRecord;
if ($this->load($customer, $phone, Yii::$app->request->post()) && $customer->save())
{
$this->store($this->makeCustomer($customer, $phone));
}
return $this->render('add', ['customer' => $customer, 'phone' => $phone]);
}
private function load (CustomerRecord $customerRecord, Phonerecord $phoneRecord,
array $post)
{
return $customerRecord->load(Yii::$app->request->post())
and $phoneRecord->load(Yii::$app->request->post())
and $customerRecord->validate()
and $phoneRecord->validate(['number']);
}
}
Latter code is from a book named "Web Application Development with Yii 2 and PHP" and it uses a transition layer between MVC and active record (if I understand it right).
$customerRecord->update() and $customerRecord->getPrimaryKey() does not help as well.
Any ideas?
P.S. data gets written to the written to the db without Problem.
I had a similar problem when trying to add a reference to a foreign table's auto-increment field. I was manually adding the row and then tried getting $record->id and $record->getPrimaryKey() but both were returning null even after the record was successfully committed to the database.
I overlooked the fact that just because I had an auto-increment field, that I didn't actually have a primary key set on the table. Yii reads the database schema and uses the table information to determine what primary keys there are and subsequently how to update the primary keys in your record after insertion. So even if your ActiveRecord definition has defined a primary key, this is not enough. Once I added the primary key to the table, everything magically worked!
try using in actionAdd
if ($this->load($customer, $phone, Yii::$app->request->post()) && $customer->save(false ))
and function store
$customerRecord->save(false);
could be only a validation problem than that prevents the proper conduct of activities, (in this case the saving of the respective model)
I have problem with saving data to m:n table layout in laravel 5. I have table appliances and table documentations, where pivot table is documentation_appliance.
Models are:
class Appliances extends Model
{
public function documentations()
{
return $this->belongsToMany('documentations');
}
}
and
class Documentation extends Model
{
public function appliances()
{
return $this->belongsToMany('appliances');
}
}
Now I try to save data to table in my Controller
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'file_name' => 'required',
]);
if($request->hasFile('file_name') ) {
$fname = $request->file('file_name')->getClientOriginalName();
$request->file('file_name')->move(
base_path() . '/public/files/documentation/', $fname
);
}
$document = new Documentation();
$document->name = $request->name;
$document->filename = $fname;
if($document->save()) {
$doc_ids = $request->documentation_appliance;
$document->appliances()->sync($doc_ids);
}
return view('backend.documentation.index', [
'documentations' => $this->documents->getDocuments(),
]);
}
Data to table documents are saved corectly, image is stored, but I have problem with saving data to pivot table. Screen displays me this error:
FatalErrorException in compiled.php line 10191:
Class 'appliances' not found
in compiled.php line 10191
nothing more, I guess I have bad use of class somewhere or am I doing bad something else? Thanks everyone for help.
according to https://laravel.com/docs/5.2/eloquent-relationships#many-to-many your table name must be appliance_documentation not documentation_appliance.
I've got a problem moving from laravel 4 to laravel 5.
I hae a test example that i downloadet some time ago in laravel 4 and it works prefectly. But when i wrote the same example it stops at some point.
I'm using ExtJS 5 for framework.
Controller:
<?php namespace App\Http\Controllers\books;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BookController extends Controller {
public function load()
{
$books = DB::table('books')->select('id','title','author','price','quantity')
->orderBy('id','asc')->get();
// dodajemo u array polje cijena koja množi cijenu i količinu
foreach ($books as $b)
{
$b->cijena = $b->price * $b->quantity;
}
die(print_r($data));
//die(print_r($books));
return Response::json($books);
//print_r($x);
}
public function create()
{
$input = Input::all();
if ($input['id'] == '')
{
$books = DB::table('books')->insertGetId(array('title' => $input['title'], 'author' => $input['author'], 'price' => $input['price'], 'quantity' => $input['quantity']));
return Response::json(array('msg'=>'New Books record successfully created.'));
}
else
{
$book = DB::table('books')->where('id', '=', $input['id']);
$book -> update($input);
return Response::json(array('msg' => 'Book successfully update.'));
}
}
public function delete($bookId)
{
//$x = $bookId;
//die(print_r($x));
$book = DB::table('books')->where('id', '=', $bookId)->delete();
}
}
Route:
<?php
Route::get('load_books', 'BookController#load');
Route::post('create', 'BookController#create');
Route::get('delete/{bookId}', 'BookController#delete');
Route::get ('/', function()
{
//return View::make('index');
return View::make('books');
});
when i open the aplication in browser i get the view and the form of ExtJS, thanks to #lukasgeiter i addet use DB & use Response and got the data shown.
In ExtJS POST methode is used to create new book
The problem now is when i try to create new book i get:
POST http://localhost/testni_server/artikli/public/books/create 500 (Internal Server Error)
And i can't figure out how to fix this problem.
Evrything is the same as in laravel 4, except it works in laravel 4, but not in laravel 5