Laravel unit test not saving to database - php

I am trying to test some things in laravel but I cant even get past the most basic part.
I want to get the results from the database. Do some things. Add them back to another table and then asset that they exist in the new table and are correctly altered.
However, it is not storing to my database. This is what I have so far
public function getUser($id)
{
return DB::raw("SELECT * FROM users WHERE id = $id");
}
public function testGetUsers()
{
$users = [97];
foreach($users as $key => $value) {
$response = $this->getUser($key);
DB::raw("INSERT INTO user_tested (user_id, response) VALUES ($key, $response)");
}
}
When I run the artisan command in the terminal I only get the warning:
get users → This test did not perform any assertions /tests/Unit/testUsers.php:17
Which I expect because there were no assertions. However the code should still have run, no? Nothing is saved in the database.
also, if someone can tell me how to log out to the terminal whilst doing this that would be really helpful in debugging.

Related

Livewire Datatables - update columns dynamically without page refresh

I have a custom reporting feature I'm trying to build. To keep it short, the user is presented with options to choose from, those options are used to build an Eloquent query that returns data from the database to the front-end, in the form of an HTML table.
I'd like to switch my HTML table out for a Livewire Datatable. To do this, I need to build columns on the fly, based on what the user selects from the filters.
The datatable:
// $cols contains all the necesarry data from the user's selection to build columns the Livewire Datatable can understand.
public function displayReport($cols)
{
// This processes the data and pushes each new column into $this->cols
foreach($cols as $key => $val) {
$instance = app()->make($val['column']);
$columnName = $val['name'];
$item = $instance->name($columnName);
$item->filterable = true;
$item->hideable = true;
array_push($this->cols, $item);
}
public function columns()
{
return $this->cols;
}
I have dd($this->cols) and it is exactly what is needed to build the datatable. The problem is with the refresh of the component (from what I can tell). Upon submitting the users selection and running the whole thing, I get the following error:
Despite my best troubleshooting efforts, I have not been able to get the table to hydrate properly upon submission of my new columns. I even put a dd($this->cols) right before return $this->cols in the column function, and it returns exactly what is expected. But it won't build the table, and it throws that error seen above.
Help is appreciated. Thank you so much. I know this is a weird and complex one.

Getting errors in php from retrieving data from mysql database in laravel

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.

Dynamic seeding in laravel 5.4

I'm extremely new to laravel and having trouble with this seeder. I feel like it should be an easy thing to do, I just don't have the right tools for it yet.
I need to populate a column with data based on a different column. More specifically, I want to take the employee_id, find where their location is in the employee table, and populate that id in the application table. This is what I have so far:
use Illuminate\Database\Seeder;
use App\Employee;
use App\Application;
class ApplicationEmployeeLocationTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$applications= Application::all();
foreach ($applications as $application)
{
$location_id = Employee::whereId($application->employee_id)->pluck('location_id')->first();
}
}
}
This returns all the ids I'm looking for as a string, but how do I put these values into location_idin the applications table? Running this seeder doesn't produce an error, but it doesn't do anything either.
Let me know if there's any other information you need, and thanks in advance.
It would be easier if you just pulled the location_id from an object. Also, to eliminate multiple hits to the database in that loop, I suggest you pull in a collection of employees (pulling from the DB only once) before the loop, and then find the right location for the employee from the collection.
The way you have it now, you go to the DB on every looped application to draw an employee. Having a collection before the loop will eliminate all those pulls.
I'll break it out into a few steps below for clarity, but you can tighten this if you wish:
$applications= Application::all();
$employees = Employee::all();
foreach ($applications as $application)
{
$emp = $employees->where('id', $application->id)->first()
$location_id = $emp->location_id;
}
To put the location for the application back into the database, you can simply save it to the application object:
foreach ($applications as $application)
{
$emp = $employees->where('id', $application->id)->first()
$location_id = $emp->location_id;
$application->location_id = $location_id;
$application->save();
}
The above is writing to the DB each time, which I was trying to avoid, but once you get this working, you can always investigate adding those applications to a collection and then saving the collection. But this should get you where you want to be.

Why suddenly I started getting No query results for model error in Laravel?

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());

Why is laravel migration failing silently?

I am converting a 12 year old frameworkless php app into a Laravel app. The old app had two separate user tables which I have merged. Merging them requires massaging the data. I created a migration to massage the data in one of my tables.
My up() function looks like this:
public function up()
{
$users = User::all();
foreach($users as $user) {
if ($user->staff_id = '0') {
$user->role = '4';
} elseif ($user->role != '1') {
$user->role = '3';
}
$user->save();
}
}
I had run a similar function in a migration moments previously which ran fine. However this one produced the following output:
myusername at local in ~/Sites/tgdp/trunk
> mamp-php artisan migrate
myusername at local in ~/Sites/tgdp/trunk
>
And when I looked in my migrations table and at the User table, it was obvious the migration had not been run.
So, to recap. No error thrown. No "Nothing to Migrate." No success response. No effect on the database. * Edit: No errors listed in the logs.
Any idea why this might have happened?
So, it turns out that the problem was that looping through and saving all of those users was very memory intensive. The solution was to give php limitless access to memory. Like so:
php -d memory_limit=-1 artisan migrate
Once I did that the code ran fine.

Categories