Laravel 5: Database doesn't save through dropdown - php

I want to save some data through dropdownlist .. after loading the page, database also fetched with the dropdown but it doesn't save after I clicked the save button. I think there is problem with Course migration table but I couldn't get it.
[Scenery is while taking courses student can take a class from the dropdown list.]
Here is my contoller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
use App\TheClass;
use Redirect;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
$input=\App\TheClass::all();
return view('course.create',compact('input'));
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
}
Here is my view page:
<html>
<head>
<title> Create Course </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" >
<h3> Create course </h3>
{!! Form::open(array('route' => 'course.store','class'=>'form-horizontal')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label>Course Code</label>
<input type="text" name="course_code" class="form-control" placeholder="Code">
</div>
<div class="form-group">
<label>Course Title</label>
<input type="text" name="course_title" class="form-control" placeholder="Title">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" placeholder="Credit">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="class_id" >
#foreach($input as $row)
<option value="{{$row->class_id}}">{{$row->class_name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
</body>
</html>
Course Table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCourseTable extends Migration
{
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('course_id');
$table->string('course_code',10);
$table->string('course_title',50);
$table->string('course_credit');
$table->integer('class_id')->unsigned();
$table->timestamps();
$table->foreign('class_id')->references('id')->on('classes');
});
}
public function down()
{
Schema::drop('courses');
}
}
The Class table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClassTable extends Migration
{
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->string('class_name',10);
$table->timestamps();
});
}
public function down()
{
//
}
}

Change {{$row->class_id}} to {{$row->id}}
Because your classes table does not have class_id column.

First of all you need to add $fillable to your model as create
method uses Mass Assignment.
Secondly I dont see any category field in migrations. Your select
has name category so in database also should be category field.
Basically here you need to use One To Many
P.S. Don't have enough points for comments so answered.

Related

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'male' in 'field list' laravel 9

to be honest idk what's wrong here in my code but i still receive this error i see all the solution here but nothing happen , is the problem in the type="radio"? i try to change it to type="checkbox" but it still appears an error """ datatype of checkbox-> boolean
my blade file : form ->
<form action="{{url('reserveinfo')}}" method="POST" enctype="multipart/form-data" >
#csrf
<!-- ******** input user data to reserve ******** -->
<div class="MaleFemale">
<div class="Male">
<input type="radio" name="male" id="ML">
<label for="ML">Male</label>
</div>
<div class="Female">
<input type="radio" name="female" id="FML">
<label for="FML">Female</label>
</div>
</div>
<div class="FullName">
<input type="text" name="fullname" placeholder="Full name">
</div>
<div class="PatientEmail">
<input type="email" name="email" placeholder="Email">
</div>
<div class="TestBirthday">
<div class="Test">
<p>Test PCR</p>
<div>
<label for="TSTFILE">
<img src="../Resources/File.png" for="TSTFILE">
Add file</label>
<input type="file" name="testpcr" id="TSTFILE">
</div>
</div>
<div class="Birthday">
<label for="Birthday">Birthday</label>
<input type="date" name="date">
</div>
</div>
<div class="DoctopPres">
<p>Doctor prescription</p>
<div>
<label for="DctrPres">
<img src="../Resources/File.png" for="DctrPres">
Add file</label>
<input type="file" name="doctorpres" id="DctrPres">
</div>
</div>
<!--########## Send request ########## -->
<div class="Reserve">
<a href="../HtmlFiles/Reserve-3-.html">
<button>Reserve</button>
</a>
</div>
Controllers code :
public function reserveinfo(Request $request){
$data = new reserveinfo;
$data->male=$request->Male;
$data->female=$request->female;
$data->fullname=$request->fullname;
$data->email=$request->email;
$data->birthday=$request->date;
$test_pcr=$request->file('testpcr');
$imagename=time().'.'.$test_pcr->getClientoriginalExtension();
$request->testpcr->move('Text-PCR-of-users',$imagename);
$data->$test_pcr=$imagename;
$Doctor_prescription=$request->file('doctorpres');
$imagename2=time().'.'.$Doctor_prescription->getClientoriginalExtension();
$request->doctorpres->move('Doctor-prescription-of-users',$imagename2);
$data->doctorpres=$imagename2;
if(Auth::id()){
$data->user_id=Auth::user()->id;
}
$data->save();
return redirect()->back();
}
routes :
Route::get('/reserve1_view',[UserController::class,'addview']);
Route::get('/reserve2_view',[UserController::class,'addview2']);
Route::post('/reserveinfo',[UserController::class,'reserveinfo']);
migrations code :
public function up()
{
Schema::create('reserve2s', function (Blueprint $table) {
$table->id();
$table->boolean('male')->nullable();
$table->boolean('female')->nullable();
$table->string('fullname')->nullable();
$table->string('email')->nullable();
$table->string('test_pcr')->nullable();
$table->string('birthday')->nullable();
$table->string('Doctor_prescription')->nullable();
$table->string('user_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('reserve2s');
}
};
and get this error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'male' in 'field list
models code :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class reserveinfo extends Model
{
use HasFactory;
}
""" nothing add to models """
thanks for reading this XD
Try this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class reserveinfo extends Model
{
use HasFactory;
protected $table = 'reserve2s';
}
I recommend you read the Laravel manual about Eloquent's naming convention.
Eloquent Model Conventions
In your second error you are using the value of the variable $test_pcr as the attribute name. Just remove the $.
// Change this
$data->$test_pcr=$imagename;
// to
$data->test_pcr=$imagename;
// Change this
$data->doctorpres=$imagename2;
// to
$data->Doctor_prescription=$imagename2;
Remembering that you should read about Eloquent to understand how this integration works with the model and the database table.

Error 500 while trying to upload an image using FilePond and Laravel Spatie

I'm trying to create items that have a picture/avatar using a form and insert them into my database, so I decided to use Laravel Spatie with the MediaCollection, but as soon as i implemented the library, I'm getting an error 500 when I submit my form.... any idea why? And how am I supposed to create my database fields so when I create a new item with a picture I submit, the picture is submitted in a "Picture" datatable and in my "item" datatable I have the foreign key "picture_id" referencing to the picture in the Picture datatable.
Item.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Item extends Model implements HasMedia
{
use HasFactory;
use InteractsWithMedia;
public function inventory_list()
{
return $this->belongsTo(InventoryList::class);
}
public function work_ticket()
{
return $this->belongsToMany(WorkTicket::class);
}
public function picture()
{
return $this->belongsTo(Picture::class);
}
}
ItemController.php:
<?php
namespace App\Http\Controllers;
use App\Models\InventoryList;
use App\Models\Item;
use App\Models\Picture;
use App\Models\TemporaryFile;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function index()
{
$inventory_lists = InventoryList::all();
$pictures = Picture::all();
return view('add-item', ['inventory_lists' => $inventory_lists,
'pictures' => $pictures]);
}
public function store(Request $request)
{
$item = new Item;
$item->name = $request->name;
$item->state = $request->state;
$item->observations = $request->observations;
$item->list_id = $request->list_id;
$item->picture_id = $request->picture_id;
$temporaryFile = TemporaryFile::where('folder', $request->avatar)->first();
if($temporaryFile){
$item->addMedia(storage_path('app/public/avatars/tmp/' . $request->avatar . '/' . $temporaryFile->filename))
->toMediaCollection('avatars');
rmdir('app/public/avatars/tmp/' . $request->avatar);
$temporaryFile->delete();
}
$item->save();
return redirect('add-item')->with('status', 'Item Form Data Has Been inserted');
}
}
add-item.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Créer un nouvel item</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
#if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<div class="card">
<div class="card-header text-center font-weight-bold">
Ajouter un nouvel item
</div>
<div class="card-body">
<form name="add-blog-post-form" id="add-blog-post-form" method="post" action="{{url('store-item')}}">
#csrf
<div class="form-group">
<label for="name">Nom</label>
<input type="text" id="name" name="name" class="form-control" required="">
</div>
<div class="form-group">
<label for="state">État</label>
<input type="text" id="state" name="state" class="form-control" required="">
</div>
<div class="form-group">
<label for="observations">Observations</label>
<textarea name="observations" class="form-control" required=""></textarea>
</div>
<div class="form-group">
Liste d'inventaire
<select name="list_id" class="form-control select2-multiple">
<option value=""></option>
#foreach($inventory_lists as $inventory_list)
<option value="{{$inventory_list->id}}">
{{$inventory_list->name}}
</option>
#endforeach
</select>
</div>
<div>
<label for="avatar">Photo</label>
<input type="file" name="avatar" id="avatar">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#section('scripts')
<script>
const inputElement = document.querySelector('input[id="avatar"]');
const pond = FilePond.create( inputElement );
FilePond.setOptions({
server: {
url: '/upload',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
}
});
</script>
#endsection
</div>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
#yield('scripts')
</body>
</html>
UploadController.php
<?php
namespace App\Http\Controllers;
use App\Models\TemporaryFile;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function store(Request $request)
{
if ($request->hasFile('avatar')) {
$file = $request->file('avatar');
$filename = $file->getClientOriginalName();
$folder = uniqid() . '-' .now()->timestamp;
$file->storeAs('avatars/tmp/' . $folder, $filename);
TemporaryFile::create([
'folder' => $folder,
'filename' => $filename
]);
return $folder;
}
return '';
}
}
2022_05_06_063218_create_temporary_files_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('temporary_files', function (Blueprint $table) {
$table->id();
$table->string('folder');
$table->string('filename');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('temporary_files');
}
};
Thanks in advance
Edit:
I got this error right before getting my Error 500, then I simply refreshed my page and I never got the following error again, just an error 500.
local.ERROR: Declaration of
Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection::jsonSerialize()
must be compatible with
Illuminate\Support\Collection::jsonSerialize(): array
{"exception":"[object]
(Symfony\Component\ErrorHandler\Error\FatalError(code: 0):
Declaration of
Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection::jsonSerialize()
must be compatible with
Illuminate\Support\Collection::jsonSerialize(): array at
/home/vagrant/code/vendor/spatie/laravel-medialibrary/src/MediaCollections/Models/Collections/MediaCollection.php:51)
[stacktrace]
#0 {main}

Troubling to show sub-categories in the Categories Dropdown list

in my code,i want to show category and sub catagory under the Category in the Products table.
Here is my categories table
1.
public function up() { Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id'); //sub category id
$table->string('name');
$table->rememberToken();
$table->timestamps();
});
}
Here is my products table
2.
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->string('product_name');
$table->timestamps();
});
}
Here is my Category Model
3.Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model { protected $guarded=[];
public function products(){
return $this->hasMany('App\Product');
}
public function parent(){
return $this->belongsTo('App\Category','parent_id','id');
}
}
Here is my Product Model
4.Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(){
return $this->hasone('class::Category');
}
}
Now here is my ProductsController.php
5.ProductsController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Product;
use Session;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function product(){
return view('admin.products.product');
}
}
Here is my product.blade.php file
<form class="form-horizontal" method="post" action="{{route('add.product')}}" name="add_product" id="add_product" novalidate="novalidate">
#csrf
<div class="control-group">
<label class="control-label">main Category </label>
<div class="controls">
<select name="category_id" id="category_id" style="width:220px;">
#foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Product Name</label>
<div class="controls">
<input type="text" name="product_name" id="product_name">
</div>
</div>
<div class="form-actions">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
I want to data like this in my product.blade.php
what data i want
thats why i use this code in product.blade.php
#foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
#endforeach
but i facing error like this
ErrorException (E_ERROR)
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (View: F:\laragon\www\flipcart\resources\views\admin\products\product.blade.php)
Previous exceptions
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (0)
There are a number of things you may want to review in this code as there are several odd bits.
The error you are getting is caused by this code:
$cat->parent()->name
You are accessing a query builder instance when you call a relationship as a method rather than a property (i.e. ->parent() rather than ->parent).
Try this instead:
$cat->parent->name
Your ternary statement should then be replaced with something like this:
$cat->parent ? $cat->parent->name . ' -- ' : ''

MethodNotAllowedHttpException in RouteCollection.php Laravel

I have problem to save name and email from user1 in table user1s that I have made .
When I enter them in textareas using html form in Laravel with route::post and function store it is not working. When I enter text and hit the button Register it outputs the following error:
MethodNotAllowedHttpException in RouteCollection.php line
You will see that I use the HTML form and that I have tried to add <input ....> into my form.
Here are my files:
route.php
<?php
Route::get('/','PageController#home');
Route::post('/','User1Controller#store');
Route::get('about','PageController#about');
welcome.blade.php
I'm not sure about the action.
After putting user1 inf into table, it should be redirected to a "Thank you" page (I have a thankyou.blade.php ) , maybe that is the problem
<form method="POST" action="">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<ul class="list-group" >
<li >
NAme
<div class="form-group" title="email" >
<textarea name="name" class="form-control" >
</textarea>
</div>
</li >
<li>Email
<div class="form-group" >
<textarea name="email" class="form-control" >
</textarea>
</div>
</li>
<li >
<div class="form-group" >
<button class="btn btn-primary">Register</button>
</div>
</li>
</ul>
</form>
migration for user1
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('card_id')->unsigned();
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::drop('notes');
}
}
user1controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class User1Controller extends Controller
{
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return view('thankyou');
}
}
pagecontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class PageController extends Controller
{
public function home()
{
$user1s= User1::all();
return view('welcome',compact('user1s'));
}
public function about()
{
return view('pages.about');
}
}
Your form is basically a registration form. I would recommend using a more meaningful name for the end point. The post route can be something like,
Route::post('/register','User1Controller#store');
Now the form action can be,
action="/register"
I corrected the typo.Thanks!
I have also changed this
Route::post('/','User1Controller#store');
and action=" " .
It works ,the only thing right now that is not good is that I should redirect to a page "Thank you" not go to anther view on the exact same page.
Because It makes a mess in the database when I reload the home page.
I'll try that and tell if it works.
Thank you people for the help! :)
Things solved,this works. I will add the code that i have added so the other can find it!
Firs of all : I haven't figured why ,but action="dir1/dir3" for me didn't work!
Here are the added things!
routes.php
Route::get('thankyou','PageController#thankyou');
***PageController.php***
public function thankyou()
{
return view('thankyou');
}
*****User1Controller.php*****
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect('/thankyou');
}

Database couldn't update through Laravel

I want to Edit my Database through Laravel Form. Edit do works but when i want to update the database it's showing the following Error.
MethodNotAllowedHttpException in RouteCollection.php line 219:
here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
return view('course.create');
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
public function show($id)
{
//
}
public function edit($id)
{
$course=Course::findOrFail($id);
return view('course.edit',compact('course'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$data=Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
public function destroy($id)
{
$data=Course::findOrFail($id);
$data->delete($input);
return redirect('course');
}
}
Here is my Edit Page:
<html>
<head>
<title> Update Course </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" >
<h3> Update course </h3>
{!! Form::open(array('route' =>['course.update',$course->course_id],'class'=>'form-horizontal')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label >Course Code</label>
<input type="text" name="course_code" class="form-control" value="{{$course->course_code}}">
</div>
<div class="form-group">
<label >Course Title</label>
<input type="text" name="course_title" class="form-control" value="{{$course->course_title}}">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" value="{{$course->course_credit}}">
</div>
<button type="submit" class="btn btn-default">Update</button>
{!! Form::close() !!}
</div>
</body>
</html>
Here is the route:
<?php
Route::resource('course','courseController');
Route::group(['middleware' => ['web']], function () {
});
If anyone can solve the problem.please help.
When you try to edit you need to add method type according this link.
Specifying different methods
You can use methods other than POST with your forms. Pass the 'method'
you want in the array argument. Valid methods are 'get', 'put',
'patch', 'post', or 'delete'.
So in your case you need to add 'method' => 'patch' to your Form::open..
So your final code in blade will look like this:
{!! Form::open([
'method' => 'PATCH',
'route' => ['course.update',$course->course_id],
'class'=>'form-horizontal'
]) !!}
Extra
I can see you are using php tags like <?php echo csrf_field(); ?>, I assume you know in Laravel you can use {{ csrf_field() }} which is equal, but since I do not have in depth knowledge about your code, so it is left to you.

Categories