Im using laravel to pull some log information from a database, but all of a sudden its stopped working, as in its not retrieving data and not returning anything. Im using vuejs to retrieve the data without page refresh, theres no problem on the front end because data can still be retrieved also in the chrome debug console its displaying as a 500 error.
Furthermore what i find weird is it works locally but not in production.
Example code of what works and what doesn't
<?php
namespace App\Http\Controllers;
use App\Log;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class LogController extends Controller
{
public function getLogData()
{
//This is the original code & it doesn't work in production!
//$data = Log::orderBy('id', 'DESC')->select('action', 'object_id', 'ip_address', 'user', 'time', 'date')->get();
//This works! But only retrieves 1 row of information
$data = Log::where('id', 1)->get();
$data = str_replace('*', "<b>", $data);
$data = str_replace('^', "</b>", $data);
return $data;
}
}
and heres the logs model, which shouldnt really affect anything but entering data into the database really but just incase anyone needs this information.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Log extends Model
{
protected $fillable = ['action', 'object_id', 'object_type', 'ip_address', 'user', 'time', 'date'];
}
Any help i get will be appreciated.
The answer to this question can be found here in detail: Limit on amount of rows retrieved MySql, Laravel
In short my Mysql query was pulling back more than my set limit of data due the the growing daily data of my logs table. Increased the limit and everything was working as usual.
I would check the php5 error file, check your php.ini for the location of the error file on the production machine. 500s missing in the logs endup in the php error file log sometimes. There can be a memory leak e.g a string too long for php memory to process it since its returing a log entry which can sometimes be long.
Also, Can you make the select statement as the first thing that you pass to the model like this (won't solve the issue at hand but its best practice to do so )
Log::select('action', 'object_id', 'ip_address', 'user', 'time', 'date')
->orderBy('id', 'DESC')
->get();
Related
So I am trying to retrieve data from MySQL database (myphpadmin) using laravel framework. I want to make a search engine that can search my data in the database, for your information I am retrieving the data from myphpadmin using xampp. Basically, I want to display the data that I will be searching for in the UI. For example, student id is = 1000, when I search 1000 it should display me with the student information.
This is my code:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class PredictionController extends Controller
{
public function predictionData(){
$datas = DB::select(DB::raw("SELECT id, sex, reason, failures, higher,absences, G1,G2,G3 from real_test;"));
return view('predictionPage', ['datas' =>$datas]);
}
public function search(){
$search_student = $_GET['search'];
$datas = DB::select(DB::raw("SELECT id, sex, reason, failures, higher,absences, G1,G2,G3 from real_test;"));
$data = $datas::where('id','LIKE','%' .$search_student. '%')->get();
return view('adminLayout.predictionPage', ['data' => $data]);
}
}
This is my code for HTML display :
I tried many things. one time I got an array to string error. Another time I got that foreach cannot identify the data (I searched about it and people say its because you do not have an array for that, but I saw one website he did the same thing as me but it displayed for him, the only difference is that he is using data from his database section).
This is my error: Class name must be a valid object or a string, and it's pointing towards $data = $datas::where ... line.
Please help, I have been trying and searching for 3 hours 😟
This is my error Right now :
https://i.stack.imgur.com/kCtbF.png
First i have to thank #aynber because of his code I came up with a solution.
So what I did is use #aynber code
$data = DB::table('real_test')->select(['id','sex','reason','failures','higher', 'absences','G1','G2','G3'])->where('id','LIKE','%' .$search_student. '%')->get();
and instead of having another $data I just put an arrow -> and added where to the search, and the answer came up to me.
Thank you aynber you have no idea how much I have tried.
My axios request (combined with Laravel) gives me a 500 error in the web console when I try to save a new question (= Frage):
"Error: Request failed with status code 500"
VueJS-method save():
save: function(){
axios.post('/api/save-frage', this.Frage) //passes the object this.Frage
.then(res => {
// nothing here
});
}
api.php:
Route::post('/save-frage','FragenController#store');
FragenController.php (Controller):
public function store(Request $request)
{
// validation coming soon :)
$frage = new Frage;
$frage->Frage = request('Fragentext');
$frage->save(); //if I comment this out, there's no error 500 :)
}
Frage.php (Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class Frage extends Model
{
protected $table = 'fragen';
protected $fillable = ['Frage']; // only field to fill is called "Frage"
}
I thought maybe the route was wrong (api.php), but if I change this, I then get a 404 error, so I guess this is correct, since otherwise there would have always been a 404 error.
Then I checked the model if maybe the table or fields were protected but this looks good to me.
What am I doing wrong here?
Thanks guys, by looking in the XHR tab, as well as in laravel.log I saw the issue:
I reused an older table ("Frage") that
didn't have the necessary "created_at" and "updated_at" columns.
has lots of other columns beside "Frage" without a default value, that needed input as well.
My solution:
add the missing two columns
send the other column values in the this.Frage also.
We have a COMMON database and then tenant databases for each organization that uses our application. We have base values in the COMMON database for some tables e.g.
COMMON.widgets. Then in the tenant databases, IF a table called modified_widgets exists and has values, they are merged with the COMMON.widgets table.
Right now we are doing this in controllers along the lines of:
public function index(Request $request)
{
$widgets = Widget::where('active', '1')->orderBy('name')->get();
if(Schema::connection('tenant')->hasTable('modified_widgets')) {
$modified = ModifiedWidget::where('active', '1')->get();
$merged = $widgets->merge($modified);
$merged = array_values(array_sort($merged, function ($value) {
return $value['name'];
}));
return $merged;
}
return $countries;
}
As you can see, we have model for each table and this works OK. We get the expected results for GET requests like this from controllers, but we'd like to merge at the Laravel MODEL level if possible. That way id's are linked to the correct tables and such when populating forms with these values. The merge means the same id can exist in BOTH tables. We ALWAYS want to act on the merged data if any exists. So it seems like model level is the place for this, but we'll try any suggestions that help meet the need. Hope that all makes sense.
Can anyone help with this or does anyone have any ideas to try? We've played with overriding model constructors and such, but haven't quite been able to figure this out yet. Any thoughts are appreciated and TIA!
If you put this functionality in Widget model you will get 2x times of queries. You need to think about Widget as an instance, what I am trying to say is that current approach does 2 queries minimum and +1 if tenant has modified_widgets table. Now imagine you do this inside a model, each Widget instance will pull in, in a best case scenario its equivalent from different database, so for bunch of Widgets you will do 1 (->all())+n (n = number of ModifiedWidgets) queries - because each Widget instance will pull its own mirror if it exists, no eager load is possible.
You can improve your code with following:
$widgets = Widget::where('active', '1')->orderBy('name')->get();
if(Schema::connection('tenant')->hasTable('modified_widgets')) {
$modified = ModifiedWidget::where('active', '1')->whereIn('id', $widgets->pluck('id'))->get(); // remove whereIn if thats not the case
return $widgets->merge($modified)->unique()->sortBy('name');
}
return $widgets;
OK, here is what we came up with.
We now use a single model and the table names MUST be the same in both databases (setTable does not seem to work even though in exists in the Database/Eloquent/Model base source code - that may be why it's not documented). Anyway = just use a regular model and make sure the tables are identical (or at least the fields you are using are):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Widget extends Model
{
}
Then we have a generic 'merge controller' where the model and optional sort are passed in the request (we hard coded the 'where' and key here, but they could be made dynamic too). NOTE THIS WILL NOT WORK WITH STATIC METHODS THAT CREATE NEW INSTANCES such as $model::all() so you need to use $model->get() in that case:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class MergeController extends Controller
{
public function index(Request $request)
{
//TODO: add some validations to ensure model is provided
$model = app("App\\Models\\{$request['model']}");
$sort = $request['sort'] ? $request['sort'] : 'id';
$src_collection = $model->where('active', '1')->orderBy('name')->get();
// we setup the tenants connection elsewhere, but use it here
if(Schema::connection('tenant')->hasTable($model->getTable())) {
$model->setConnection('tenant');
$tenant_collection = $model->get()->where('active', '1');
$src_collection = $src_collection->keyBy('id')->merge($tenant_collection->keyBy('id'))->sortBy('name');
}
return $src_collection;
}
}
If you dd($src_collection); before returning it it, you will see the connection is correct for each row (depending on data in the tables). If you update a row:
$test = $src_collection->find(2); // this is a row from the tenant db in our data
$test->name = 'Test';
$test->save();
$test2 = $src_collection->find(1); // this is a row from the tenant db in our data
$test2->name = 'Test2'; // this is a row from the COMMON db in our data
$test2->save();
dd($src_collection);
You will see the correct data is updated no matter which table the row(s) came from.
This results in each tenant being able to optionally override and/or add to base table data without effecting the base table data itself or other tenants while minimizing data duplication thus easing maintenance (obviously the table data and population is managed elsewhere just like any other table). If the tenant has no overrides then the base table data is returned. The merge and custom collection stuff have minimal documentation, so this took some time to figure out. Hope this helps someone else some day!
I don't know why I started getting the following error while working on Laravel application.
No query results for model [App\Hotspot].
Here is my Model Function to get user's hotspots.
public function hotspots()
{
return $this->hasManyThrough(Hotspot::class, Operator::class, 'id', 'operator_id');
}
and here is how I am executing the query to get data.
$hotspotId = $id;
$hotspot = Auth::user()->hotspots()->findOrFail($hotspotId);
I started getting this error suddenly. I don't know what went wrong! I tried to find solution on internet but they are totally different cases.
As shown in https://laravel.com/docs/5.4/eloquent-relationships, section Has Many Through.
return $this->hasManyThrough(Hotspot::class, Operator::class, 'user_id', 'operator_id', 'id');
This is necesary due to you are first connecting the Hotspots to he User, after that you are connecting he operations to the Hotspots. therefor his order is correct.
Reason for it working certain times, is because of id clashes, if you used Uuids this code would never work. You can also debug this solution with he following.
DB::enableQueryLog();
// General i feel like Auth::user()->hotspots->where('id', $hotspotId)->first() is more Laravel'sh.
// Like this you will query a lot, if used in wrong cases.
$hotspot = Auth::user()->hotspots()->findOrFail($hotspotId);
dd(DB::getQueryLog());
Or you can get the raw sql, sometimes provides you with a different view.
dd(Auth::user()->hotspots()->toSql());
i'm working on a web app using eloquent and laravel 5. The problem is that i'm trying to delete a row of a table called "Ponderacion" but when i send the ajax delete request, the server stops (it stops the execution of the routed function but the server keeps running) at the line where the delete is, without throwing any errors.
Here is the Model of Ponderacion:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ponderacion extends Model{
protected $table = 'Ponderacion';
protected $fillable = array('ponderacionidearea', 'ConfiguracionDeExamenifconf', 'peso');
public $timestamps = false;
}
Here is the function in the Controller:
public function deleteConfig(Request $request){
error_log('deleting');
$s_area = Area::where('nombre', '=', $request->input('s_area'))->first();
error_log(count($s_area->Configuracion->first()->Ponderacion));
//DB::statement('delete from Ponderacion where idponderacion = 22');
foreach ($s_area->Configuracion->first()->Ponderacion as $ponderacion){
error_log($ponderacion->peso);
try{
$ponderacion->delete();
}catch(Exception $e){
error_log('failure');
}
}
//$s_area->Configuracion->first()->Ponderacion->delete();
error_log('succesfully deleted');
$s_area->Configuracion->first()->delete();
}
I can succesfully print the property "peso" of ponderacion but i'm unable to delete it. Ponderacion has Foreign Keys to other table but no other table has a reference to Ponderacion. I'm able to delete a row of Ponderacion with DB::statement but that is not secure.Succesfully deleted never shows on console.
Thanks in advance.
For AJAX testing, I always prefer to directly test via a GET request first where possible and then layer on the AJAX POST once I know the underlying code works.
In this case, the server is likely throwing a Fatal Error, which will then return a 500 error for an AJAX request and no further information. There is a good SO question that deals with catching Fatal Errors.
I would check your includes for your class. In Laravel 5, the default namespace is not the global namespace for Controllers. You'll need to add a \ before Exception or add use Exception to the top of your class file.
Two tips as well:
Use SoftDeletes on your model. It's better to track and audit your database records if you never really remove a row. DB storage space is really cheap and Laravel will automatically skip the deleted rows when querying.
Use an IDE for development. A lot of these errors can be caught before run-time by a good compiler.