Creating new data using POST dosen't work in laravel 5 - php

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

Related

Axios GET with params being ignored

Newbie to all the tech I'm using here.
Trying to query a table using Axios in Laravel with Vue.js. Here's what I got:
from my component's <script>
this.axios
.get('http://localhost:8000/api/tasks', {params: {vid: this.properties[0].vid}})
.then(response => {
this.tasks = response.data;
console.log(response)
})
Regardless of what vid is in the params, the response contains ALL of the table's rows.
I do know that this may have something to do with api.php, and the Controller associated with the request. I'll post those to be verbose.
routes/api.php
Route::middleware('api')->group(function () {
Route::resource('vehicles', VehicleController::class);
Route::resource('tasks', TaskController::class);
Route::get('tasks?={vid}', [TaskControler::class, 'search']);
});
Controllers/TaskController.php
class TaskController extends Controller
{
//
public function index() {
$tasks = Task::all()->toArray();
return $tasks;
}
public function store(Request $request){
$task = new Task([
'make' => $request->input('make'),
'model' => $request->input('model'),
'year' => $request->input('year'),
'mileage' => $request->input('mileage'),
'type' => $request->input('type'),
'VIN' => $request->input('VIN')
]);
$task->save();
}
public function show($tid){
$task = Task::find($tid);
return response()->json($task);
}
public function update($tid, Request $request){
$task = Task::find($tid);
$task->update($request->all());
return response()->json('Task Updated!');
}
public function destroy($tid){
$task = Task::find($tid);
$task->delete();
return response()->json('Task Deleted!');
}
}
I tried for a while to mess around with api and the controller, but to no avail. Most of the questions asked here give "just use params" as an answer, but despite my best efforts I don't seem to be able to get away with "just" params (willing to be proven wrong.)

Write in DB doesn't work in Controller, but works in view - Laravel

I'm trying to write some data in a DB after clicking on a save button.
During my development I was writing successfully in my DB with PHP code in my view, but the PHP code was ran when the page was loaded and not when my button was clicked.
What I did is a redirection to an address that call a function in my controller and then, that redirect to a login page.
Here is my controller's code:
<?php
namespace App\Http\Controllers;
use JavaScript;
use Illuminate\Support\Facades\DB;
class bus_confirmationController extends Controller{
public function test(){
$results = DB::select('select bus_direction from bus_line where card_uid = "0xcb009299"', array(1));
JavaScript::put([
'selectionData' => $results
]);
return view('bus_confirmation');
}
public function postRequest(){
DB::table('bus_line')->insert(
array('ID' => '', 'bus_direction' => '77t', 'card_uid' => '0xcb009299')
);
return view('home');
}
}
Here is my view's code:
[...]
<div class="panel panel-default" id="save" onclick="savedata()" >
SAVE
</div>
[...]
<script type="text/javascript">
function savedata() {
var toReturn = [];
var data = ["88t", "85t","77t","redLinet"];
for (i = 0; i < data.length; i++) {
var image = document.getElementById(data[i]).style.visibility;
if (image==="visible" || image===""){
toReturn.push([data[i], "visible"]);
}
}
window.location = 'Bus_confirmationSend';
//Where I used to do my request to write my data
/*DB::table('bus_line')->insert(
array('ID' => '', 'bus_direction' => '88t', 'card_uid' => '0xcb009299')
);*/
console.log(toReturn);
}
</script>
Here is what's inside web.php
Route::get('/bus_confirmationSend', 'bus_confirmationController#postRequest');
I know my connexion to my database is working as the function 'test' from the controller works, I can retrieve data from my DB. I also know that my first redirection to 'bus_directionController' works as the second redirection to 'home' works.
Am I missing something? I really don't understand what can be wrong here.
It may be because you have window.location = 'Bus_confirmationSend'; but your route starts with lower case b

The requested URL was not found on this server but works local

I have a Laravel setup where I can add files and remove them. Now when I try to remove icons on my site on the server I get
Not Found
The requested URL /icons/24 was not found on this server.
Uploading the files and retrieving the files works. When I test it locally it works. And I do it the exact same way as with images, video files and audio files, and those all work on the server.
To debug it I also added the show() function in the controller, and that one also gives the same problem. What is going on?
routes/web.php: (partially)
Route::get('iconFile/{id}','IconController#iconFile');
Route::get('imageFile/{id}','ImageController#imageFile');
Route::get('audioFile/{id}','AudioController#audioFile');
Route::get('videoFile/{id}','VideoController#videoFile');
Route::get('signlanguageFile/{id}','SignlanguageController#signlanguageFile');
Route::group(['middleware' => ['auth']], function() {
Route::post('image-upload-with-validation',['as'=>'postimage','uses'=>'ImageController#postImage']);
Route::post('icon-upload-with-validation',['as'=>'posticon','uses'=>'IconController#postIcon']);
Route::resource('texts', 'TextController');
Route::resource('icons', 'IconController');
Route::resource('images', 'ImageController');
Route::resource('videos', 'VideoController');
Route::resource('signlanguages', 'SignlanguageController');
Route::resource('audios', 'AudioController');
});
IconController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Icon;
use Storage;
class IconController extends Controller
{
public function iconFile($id)
{
$icon = Icon::find($id);
$contents = Storage::disk('local')->get('uploads/icons/'.$icon->file);
$response = Response($contents);
$response->header('Content-Type', 'icon');
return $response;
}
public function show($id)
{
$icon = Icon::find($id);
$data = [
'icon' => $icon
];
echo $icon;
//return view('icon', $data);
}
public function postIcon(Request $request)
{
$this->validate($request, [
'icon_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
]);
$iconName = time().'.'.$request->icon_file->getClientOriginalExtension();
$request->icon_file->move(storage_path('app/uploads/icons'), $iconName);
$icon = new Icon;
$icon->parent_id = $request->parent_id;
$icon->file = $iconName;
$icon->save();
return back()
->with('success','You have successfully uploaded an icon.')
->with('icon',$iconName);
}
public function destroy($id)
{
$icon = Icon::find($id);
$section_id = $icon->parent_id;
Storage::delete('uploads/icons/'.$icon->file);
$icon->delete();
return redirect('/section/'.$section_id)->with('success','Icon deleted.');
}
}
Update:
i tried replacing the resource route to Route::resource('iconz', 'IconController'); (with a z) and then it works! Changing it back to "icons" makes it stop working again. Could icons be some kind of reserved word?
Also tried php artisan route:clear which didn't help.

Laravel 5.2 MongoDB & MySQL in Same App Error

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'
];
}

Datatable JSON parsing error

I am trying to display some data in a datatable in my laravel project but I encounter an error which says my data is not in the correct format I know the data is in the correct format as I have other datatables using the same data here is my controller:
<?php
namespace App\Http\Controllers;
use Datatable;
use View;
use App\Models\EC2Instance;
use App\Models\ChangedProperties;
use Illuminate\Support\Facades\Input;
use App\Models\ChangelogItem;
class ChangedPropertiesController extends Controller {
protected $layout = 'changed_properties';
public function details($changelog_item_id)
{
$changed_property = new ChangedProperties;
$changed_properties = $changed_property->where('changelog_item_id', $changelog_item_id)->get();
$table = Datatable::table()
->addColumn(
'Changed Property', 'Change Type', 'Changelog Item ID', 'Previous Value', 'Updated Value'
)
->setUrl('/changed_properties/'. $changed_properties)
->noScript();
return View::make('changed_properties')
->with('property',$changed_properties)
->with('table', $table);
}
public function instance_details($changelog_item_id)
{
$query = ChangedProperties::select(array('resource_id',
'resource_type',
'changed_property',
'change_type',
'previous_value',
'updated_value',
'changelog_item_id'
))
->get();
return Datatable::collection($query)
->showColumns(
'changed_property', 'change_type','changelog_item_id', 'previous_value', 'updated_value')
->searchColumns( 'changed_property', 'change_type', 'previous_value', 'updated_value')
->orderColumns( 'changed_property', 'change_type', 'previous_value', 'updated_value'
)
->make();
}
}
and routes:
/Homepage Route
Route::get('/', 'CRUDController#users');
// Route which populates datatable in homepage
Route::get('search', array('as' => 'instance.search', 'uses' => 'CRUDController#instances'));
//route which renders instance details
Route::get('/instance_details/{instance_id}','DetailsController#details');
//route which links to individual instance details
Route::get('/ec2_instance/{resource_type}/{resource_id}',array('as'=>'InstanceId', 'uses'=>'DetailsController#instance_details'));
//route which renders changed properties for changelog item
Route::get('/changed_properties/{changelog_item_id}/','ChangedPropertiesController#details');
//route which links to individual instance details
Route::get('/changed_properties/{changlog_item_id}/',array('as'=>'ChangelogItemId', 'uses'=>'ChangedPropertiesController#instance_details'));
Route::resource('sns', 'SNSController');

Categories