Add date into table which is in relation with product in Laravel 6 - laravel

I have product and auction table. I want to add auction deadline on a specific table using form. when I submit the form the product_id in auction table is not populated and deadline shows time on which form is submited.
Here what I am trying:
I want that the create form get the deadline and store in auction table with product id so I can access it in show method of product.
create.blade.php
#extends('layouts.app')
#section('content')
<div class="mt-3" style="margin-left: 50px;">
<h2>Add new product</h2>
{!! Form::open(['action' => 'ProductsController#store', 'method' => 'POST', 'enctype' =>
'multipart/form-data', 'class' => 'w-50 py-3']) !!}
<div class="form-group">
{{Form::label('name', 'Product Name')}}
{{Form::text('name', '', ['class' => 'form-control', 'placeholder' => 'Product Name'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Product Description')}}
{{Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Product Description', 'rows' => '4'])}}
</div>
<div class="form-group">
{!! Form::Label('category', 'Category') !!}
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('price', 'Product Price')}}
{{Form::number('price', '', ['class' => 'form-control', 'placeholder' => 'Product Price'])}}
</div>
<div class="form-group">
{{Form::label('deadline', 'Auction Deadline')}}
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('image', 'Product Image')}}
{{Form::file('image', ['class' => '', 'placeholder' => 'Product Image'])}}
</div>
{{Form::submit('Upload Product', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'price', 'description', 'image',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function auction()
{
return $this->hasOne('App\Auction');
}
}
ProductsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Product;
use App\Category;
use App\Auction;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::all();
$products = Product::with('category')->latest()->paginate(3);
return view('products.index' ,compact('categories', 'products'));
}
public function create()
{
$categories = Category::all(['id', 'name']);
return view('products.create', compact('categories',$categories));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$product->save();
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
return redirect('/products')->with('success', 'Product Created');
}
public function show($id)
{
$product = Product::find($id);
return view('products.show', compact('product'));
}
}

you are just creating auction, where is the relation? Delete $product->save(); line. After the $auction->save(); add this line:
$product->auction()->associate($auction);
$product->save();
Final Store method
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
$product->auction()->associate($auction);
$product->save();
return redirect('/products')->with('success', 'Product Created');
}
Update for Irrelevant Blade problem
This line is wrong:
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
You are using blade close string tag in blade string tag.
Should be:
{{Form::date('deadline', '', ['class' => 'form-control'])}}
If auction variable has been passing from controller this will work

Related

How to break line in textarea in laravel and then echo it by foreach loop?

The name of my controller is ProductController, This is my controller
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'product_detail' => 'required',
'product_image' => 'required',
'admin_name' => 'required',
]);
$product_image = $request->file('product_image');
$new_name = rand().'.'.$product_image->getClientOriginalExtension();
$product_image->move(public_path('product_image'), $new_name);
$form_data = array(
'product_image' => $new_name,
);
// Product::create($form_data);
$product = Product::create([
'product_name' => $request->input('product_name'),
'product_detail' => $request->input('product_detail'),
'admin_name' => $request->input('admin_name'),
'product_image' => $new_name,
]);
return redirect('products')->with('success', 'Data Added successfully.');
}
This is my index page where I want to echo it, I have doubt in Product_detail
#foreach($products as $product)
<div class="col-lg-4 col-md-6 portfolio-item filter-Interior">
<div class="portfolio-wrap">
<div class="portfolio-info">
<h4>{{$product->product_name}}</h4>
<p>
<ul style="color: white">
<li>{{$product->product_detail}}</li>
</ul>
</p>
You can use php's inbuilt function nl2br() or you can explode by PHP_EOL and then run the for loop for unordered list.
<p>{!! nl2br($body) !!}<p>
<!-- OR -->
<ul>
#foreach (explode(PHP_EOL, $body) as $item)
<li>{{ $item }}</li>
#endforeach
</ul>

How to upload excel file in Laravel using laravelcollective?

I have a problem when import data xlsx using package fast excel.
I wanna input excel files include the Id from different model like following below
app/http/clustercontroller :
public function Import($id)
{
$model = Cluster::findOrFail($id);
return view('components.Admin.import', compact('model'));
}
public function StoreImport($id, Request $request)
{
//VALIDASI
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx',
]);
if ($request->hasFile('file')) {
$file = $request->file('file'); //Get File
$collection = (new FastExcel)->import($file, function ($line) use ($id) {
return Soal::create([
'soal' => $line['Soal'],
'image' => $line['Image'],
'A' => $line['A'],
'B' => $line['B'],
'C' => $line['C'],
'D' => $line['D'],
'E' => $line['E'],
'kunci' => $line['Kunci'],
'cluster_id' => $id
]); //Import File
});
}
}
resource/admin/import.blade.php :
{!! Form::model($model, [
'route' => $model->exists ? ['cluster.soal.store', $model->id] : 'cluster.soal.create',
'method' => $model->exists ? 'POST' : 'POST',
'files' => true
]) !!}
<div class="form-group">
<label for="" class="control-label">Cluster</label>
{!! Form::text('cluster', null, ['class' => 'form-control', 'id' => 'cluster']) !!}
</div>
<div class="form-group">
<label for="" class="control-label">File .xlsx</label>
{!! Form::file('files') !!}
</div>
{!! Form::close() !!}
the code above displays the form, but when I click submit there is no response
You don't seem to return a response in your Controller method, so that's one reason I can think of. I assume your models are stored?
Things you could do to improve:
Return a view or, even better, redirection after finishing the import
Surround your code with try/catch blocks

what is the correct way of form validation in laravel?

I have just created the form and action is PagesController#check and the validation is as follows:
#extends('layout')
#section('content')
<div class = "container">
{!! Form::open(['action' => 'PagesController#check' , 'method' => 'POST']) !!}
<div class = "form-group">
{{ Form::label('country','Country')}}
{{ Form::text('country','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('age','Age')}}
{{ Form::number('age','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('marks','Marks')}}
{{ Form::number('marks','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('description','Description')}}
{{ Form::textarea('description','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
{{ Form::submit('Submit' , ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
And the check() method in the PagesController is like this:
public function check(Request $request){
$this->validate($request, [
'country' => 'required',
'age' => 'required',
'marks' => 'required',
'description' => 'required'
]);
return 123;
}
Why is it then it is throwing the following error:
(2/2) ErrorException
Action App\Http\Controllers\PagesController#check not defined. (View: C:\wamp64\bin\apache\apache2.4.23\htdocs\website\resources\views\profiles.blade.php)
Here is the whole PagesController controller:
class PagesController extends Controller
{
public function home() {
return view('welcome');
}
public function about() {
$title = 'This is the about page';
return view('about')->with('title',$title);
}
public function show() {
$yomads = person::all();
return view('show')->with('yomads',$yomads);
}
public function profiles(){
return view('profiles');
}
public function check(Request $request){
$this->validate($request, [
'country' => 'required',
'age' => 'required',
'marks' => 'required',
'description' => 'required'
]);
return 123;
}
}
The error most likely has to do with the route (or lack of it) in app/Http/routes.php - check that it is properly defined there.
Furthermore, it is good practice to create custom request classes. Have a look at Form Request Validation
These can be generated with artisan:
php artisan make:request Profile
Then use it, as you were using the standard request:
public function check(ProfileRequest $request) {
[...]

Model not inserting array data

When I submit my form my controller[] array post does not work throws errors.
Error 1
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: mysqli/mysqli_driver.php Line Number: 544
Error Number: 1054 Unknown column 'Array' in 'field list' INSERT INTO
user_group (name, controller, access, modify) VALUES
('Admin', Array, '1', '1') Filename:
C:\Xampp\htdocs\riwakawebsitedesigns\system\database\DB_driver.php
Line Number: 331
It is not inserting the controller names. Not sure best way to fix?
Model
<?php
class Model_user_group extends CI_Model {
public function addUserGroup($data) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $this->input->post('controller'),
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
?>
Controller
<?php
class Users_group extends Admin_Controller {
public function index() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->input->post('name') !== FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
$ignore = array(
'admin',
'login',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['controllers'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
if (!in_array($controller, $ignore)) {
$data['controllers'][] = $controller;
}
}
if ($this->input->post('name') !== FALSE) {
$data['controller'] = $this->input->post('controller');
} else {
$data['controller'] = $user_group_info['controller'];
}
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/user/users_group_form.tpl', $data);
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->addUserGroup($this->input->post());
redirect('admin/users_group');
}
}
}
?>
View
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php $data1 = array('id' => 'name', 'name' => 'name', 'class' => 'form-control', 'value' => $name);?>
<?php echo form_input($data1);?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<?php foreach ($controllers as $controller) {?>
<tbody>
<tr>
<td><?php echo $controller;?>
<input type="hidden" name="controller[]" value="<?php echo $controller;?>" />
</td>
<td>
<select name="access" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
<td>
<select name="modify" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<?php echo form_close();?>
The error is because you cannot insert php-array in database.
Instead store comma separated values.
In your model change data array as below:
public function addUserGroup($data) {
$controllers = $this->input->post('controller');
$name = $this->input->post('name');
$access = $this->input->post('access');
$modify = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => $name,
'controller' => $controllers[$i],
'access' => $access,
'modify' => $modify
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
}
Your controller hidden field is an array. You're passing this array to your addUserGroup function, which is trying to insert this array into the database. It's implicitly trying to convert this array to a string. Maybe try changing your function to this:
'controller' => $this->input->post('controller')[0],
Problem fixed foreach in model Thanks for the ideas on how to fix problems every one.
foreach ($this->input->post('controller') as $controller) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $controller,
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources