Laravel save related data in database - laravel

I want to save question_id in answer table using post form
I tried to use foreach or functions but i always got null data
Controller
public function store(Request $request, Survey $survey)
{
$request->validate([
'answer' => 'required',
]);
$survey->option_name = unserialize($survey->option_name);
$answers = new Answer([
'answer' => $request->get('answer'),
'commentaire' => $request->get('commentaire'),
'user_id' => auth()->id(),
'last_ip' => request()->ip(),
'question_id' => $survey->questions,
'survey_id' => $survey->id,
]);
$answers->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
answers table
question table's row :
id
survey_id
title
timestamp
I got always null data or i tried using where but i got errors like id index doesn't exists...

View :
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endempty
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}

Related

Error store data laravel when have image in pages

I am insert data product with images in dashboard, when I try to order the product I have error 404 not found and the URL showing value database in table like http://127.0.0.1:8000/shops/order/[%7B%22id%22:2,%22category_id%22:1,%22name_product%22:%22asdasd%22,%22harga%22:123123123,%22image%22:%22product-images//HapOzHmJPim1kIfmIeCM21xesCnIbR5Z7lpzcO8M.jpg%22,%22published_at%22:null,%22created_at%22:%222022-05-23T16:25:00.000000Z%22,%22updated_at%22:%222022-05-23T16:25:10.000000Z%22,%22kategori%22:%7B%22id%22:1,%22name_category%22:%22Top%22,%22created_at%22:%222022-05-23T16:22:40.000000Z%22,%22updated_at%22:%222022-05-23T16:22:40.000000Z%22%7D%7D].
But when I am insert data product without images in dashboard, and then I try to order the product is successful.
This is my route
Route::post('/shops/order/{shop:id}', [OrderController::class, 'store']);
This is OrderController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use App\Models\Shop;
class OrderController extends Controller
{
public function store(Request $request)
{
$createOrder = $request->validate([
'user_id' => 'required',
'name_product_id' => 'required',
'size' => 'required',
'no' => 'required',
'address' => 'required'
]);
Order::create($createOrder);
return redirect('shops/order/{shop:id}')->with('success', 'Order is successfully!');
}
}
This is my views
#extends('layouts.main')
#section('container')
<div class="container">
<div class="row mt-5">
#foreach ($shops as $shop)
<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4">
<img src="{{ asset('storage/' . $shop->image) }}" alt="{{ $shop->name_product }}" class="img-fluid rounded-start" style="max-height: 400px; overflow:hidden">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{{ $shop->name_product }}</h5>
<p>Jenis {{ $shop->category->name_category }}</p>
<p class="card-text fw-bold">Rp.{{ $shop->price }}</p>
</div>
</div>
</div>
</div>
#endforeach
</div>
<div class="row mt-5">
<div class="col align-self-center">
#if (session()->has('success'))
<div class="alert alert-success text-center" role="alert">
{{ session('success') }}
</div>
#endif
</div>
</div>
<form method="POST" action="/shops/order/{{ $shops }}" class="row g-2" enctype="multipart/form-data">
#csrf
<h3 class="text-center mt-2">Detail Delivery</h3>
<div class="col-md-6">
<div class="mb-3">
<select class="form-select" name="user_id" hidden>
#foreach ($users as $name)
<option value="{{ $name->id }}">{{ $name->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<select class="form-select" name="name_produk_id" hidden>
#foreach ($shops as $shops_id)
<option value="{{ $shops_id->id }}">{{ $shops_id->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<label for="address" class="form-label">Address</label>
<textarea class="form-control" #error('address') is-invalid #enderror id="address" name="address" required>
</textarea>
</div>
</div>
<div class="col-md-4">
<label for="size" class="form-label mt-3">Select size :</label>
<select class="form-select" name="size">
<option selected>S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<div class="mt-3">
<label for="no" class="form-label">Nomor Whatsapp</label>
<input class="form-control" #error('no') is-invalid #enderror id="no" name="no" required autofocus">
</div>
<button type="submit" class="btn btn-primary mt-5">Buy Now</button>
</div>
</form>
</div>
#endsection

how to display pdf in embed tag after click button?

I have a form with a filter and a submit button. I would like to display a pdf in an embed tag on the same page with the filter fields used when generating the pdf with Dompdf. Thanks in advance.
here is the form :
#section('content')
<!-- Your html goes here -->
<div class='panel panel-default'>
<div class='panel-heading'>Customer Statement</div>
<div class='panel-body'>
<form method='get' action="{{ route('getStatement') }}" id="statementForm">
#csrf
<div class="row">
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="start_date"><strong>Start Date</strong></label>
<input type="date" required name="start_date" value="{{ date('Y-m-d') }}"
class="form-control" id="start_date">
</div>
</div>
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="end_date"><strong>End Date</strong></label>
<input type="date" required name="end_date" value="{{ date('Y-m-d') }}"
class="form-control" id="end_date">
</div>
</div>
</div>
<div class='col-sm-12 form-group'>
<label> Customers :</label>
<select style="font-size: 12px; width:100%" id="customer_id" name="customer_id"
class="select2 mb-2 select2-multiple">
<option value=''> Choose </option>
#if ($customers)
#foreach ($customers as $item)
#php $selected = ''; #endphp
#if (isset($customerdirect) == $item->id)
#php $selected = 'selected'; #endphp
#endif
<option data-name="{{ $item->name }}" value='{{ $item->id }}' {{ $selected }}>
{{ $item->name }} </option>
#endforeach
#endif
</select>
</div>
</div>
<div class='panel-footer'>
<input type='submit' class='btn btn-success' value='Generate'/>
</div>
</form>
</div>
#endsection
the code in controller
public function getStatement(Request $request)
{
$pdf = PDF::loadView('customerslocations::customerstatementpdf');
return $pdf->stream();
}

Laravel : save radio group with difference key

I want to save radios group in database with different question_id
I tried to use form with radio's input have name=answer
controller :
public function store(Request $request, Survey $survey)
{
$question = \App\Question::where('survey_id', '=' , $survey->id)->get();
$request->validate([
'answer'=>'required'
]);
$arr = $request->except('_token');
$newAnswer = new Answer();
$newAnswer->answer = request()->get('answer');
foreach ($survey->questions as $key=>$question){
$newAnswer->question_id = $question->id;
}
$newAnswer->user_id = Auth::id();
$newAnswer->last_ip = request()->ip();
$newAnswer->survey_id = $survey->id;
$newAnswer->commentaire = request()->get('commentaire');
givePoint(new VoteAdded($newAnswer));
$newAnswer->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
<div id="Create" class="col-12" style="display:none;">
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
<div class="text-center">
<img class="rounded"
src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
alt="Grapefruit slice atop a pile of other slices" />
</div>
<hr>
#foreach ($survey->questions as $question)
<p class="flow-text">Question {{ $zero++}} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer[{{$question->id}}]" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#endforeach
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}
</div>
Tables :
i have already made it :
Answer table = id, survey_id , question_id , answer . commentaire ,
timestamp
Survey table : id title ...
question table : id , suvey_id , option_type , options
I got in my database a array: ["question_id" = "value"]
what a want is for example i have 2 questions , in my database i want to save 2 row with some survey id but different question id
could you help me to do that ?
-Since 1 survey can have many questions create a separate table for questions like survey_questions
-You can insert in multiple tables at the same time by writing insert queries for the survey and survey questions table separately and wrapping it in a transaction. In Laravel, you can do something like
try{
DB::transaction();
//insert in survey table
//insert in survey questions table
DB::commit();
} catch(\Exception $e){
DB::rollback()
}

Editing user info using laravel

I've built a cms interface for the admin in my website. among other things the admin can add\edit users info using forms.
when I send the edit form I keep getting this error: Column not found: 1054 Unknown column 'updated_at' in 'field list' which suggests that the DB update is trying to save all of the request indexes (which contains values of columns from other table) and not just the one I'm trying to update.
I've manage to track the problem to one line $user_role->save();.
the lines above that do what their suppose to (finding thr correcct user_role and change its value).
Here is my code
Model
static public function update_user($request, $id){
$image_name = '';
if( !empty($request['profile_image']) && $request->hasFile('profile_image') && $request->file('profile_image')->isValid() ){
$file = $request->file('profile_image');
$image_name = date('Y.m.d.H.i.s') . '-' . $file->getClientOriginalName();
$request->file('profile_image')->move( public_path() . '/images/profile-images/' , $image_name);
$img = Image::make( public_path() . '/images/profile-images/' . $image_name );
$img->resize(370, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save();
}
$user = self::find($id);
$user->name = $request['name'];
$user->email = $request['email'];
$user->phone = $request['phone'];
if( !empty($request['password']) ){
$user->password = bcrypt($request['password']);
}
if(!empty($image_name)){
$user->profile_image = $image_name;
}
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->save();
}
$user->save();
Session::flash('sm', 'Your profile has been updated');
Session::flash('sm-position', 'toast-top-center');
Session::put('user_name', $request['name']);
}
View
<div class="row">
<div class="span9">
<div class="content">
<div class="module message">
<div class="module-head">
<h3><b>Edit Product</b></h3>
</div><br>
<div class="content">
<div class="module message">
<div class="module-body">
<form action="{{ url('cms/users/' . $user->id) }}" method="POST" novalidate="novalidate" autocomplete="off" enctype="multipart/form-data">
<div class="module-body">
#method('PUT')
#csrf
<input type="hidden" name="user_id" value="{{ $user->id}}">
<div class="form-group">
<div class="input-group mb-3">
<div class="w-100 field-input-cms">
<label for="category-id" class="input-group-text h-50"><span class="text-danger">*</span><b> Permissions:</b></label>
<select name="role_id" class="custom-select span-8">
<option #if ( $user->role_id == 8 ) selected="selected" #endif value="8">Admin</option>
<option #if ( $user->role_id == 2 ) selected="selected" #endif value="2">Regular</option>
</select>
</div>
<small class="text-muted help-text">Please select one option</small><br>
<span class="text-danger"> {{ $errors->first('category_id') }}</span>
</div>
<div class="w-100 field-input-cms">
<label for="name" class="input-group-text h-100"><span class="text-danger">*</span><b> Name:</b></label>
<input type="text" value="{{ $user->name }}" name="name" style="width:100%" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted help-text">Name of user</small><br>
<span class="text-danger"> {{ $errors->first('name') }}</span>
<div class="field-input-cms w-100">
<label for="email" class="input-group-text"><span class="text-danger">*</span><b> Email:</b></label>
<input type="text" value="{{ $user->email }}" name="email" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Email of user</small><br>
<span class="text-danger"> {{ $errors->first('email') }}</span>
<div class="field-input-cms w-100">
<label for="phone" class="input-group-text"><span class="text-danger">*</span><b> Phone:</b></label>
<input type="text" value="{{ $user->phone }}" name="phone" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Phone number of user</small><br>
<span class="text-danger"> {{ $errors->first('phone') }}</span>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="profile_image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" name="profile_image" for="inputGroupFile01">Choose file</label>
</div>
</div>
<small class="text-muted help-text">Image must be: jpg, jpeg, png, gif. Max: 5mb</small><br>
<span class="text-danger"> {{ $errors->first('profile_image') }}</span>
</div>
<div class="form-group">
<img id="cms-profile-image" src="{{ asset('images/' . $user->profile_image) }}" >
</div><br>
<a class="btn btn-inverse" href="{{ url('cms/users') }}">Cancel</a>
<input type="submit" value="Save Product" name="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div> <!--/.content-->
</div><!--/.span9-->
</div>
Image of the error gaven by laravel
I should mention that if I comment out this code:
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->update();
}
all the values are saved correctly.
If your users table doesn't have created_at and updated_at columns you should set:
public $timestamps = false;
in your User model.
Laravel by default assumes you have those fields for tables. So whenever record is created/updated it will automatically set/update those fields.
Alternatively you can update your table structure to add those fields and then those fields will be automatically handled by Laravel (in such case don't set timestamps to false).
You might be interested to read about Eloquent conventions

How to display selected tags in select option value in laravel?

This is my Post Create View
<div class="col-lg-12">
<form action="{{ route('admin.post.store') }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ old('title') }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ old('body') }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-success btn-block">Publish</button>
</form>
</div>
Tags have many to many relationship.
Here I can select many tags, but in the post edit view I cant see the selected tags that selected by me in the post create view.
I want to show selected tags in select option value and edit theme.
post update methods:
public function edit(Post $post)
{
$tags = Tag::all()->pluck('name', 'id');
$cats = Category::all();
return view('admin.post.edit', compact(['post', 'cats', 'tags']));
}
public function update(Post $post, Request $request)
{
$this->validate($request, [
'title' => 'required|min:3|max:255',
'slug' => 'nullable|string',
'image' => 'sometimes|mimes:jpeg,bmp,png,jpg,gif',
'body' => 'required',
'category' => 'nullable',
'views' => 'nullable',
'tags' => 'nullable',
]);
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->category_id = $request->category;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldfilename = $post->image;
$post->image = $filename;
Storage::delete($oldfilename);
}
$post->save();
$post->tags()->sync($request->tags, false);
Session::flash('update', 'Post Updated Successfully');
return redirect()->route('admin.post.index');
}
post edit view:
<div class="col-lg-12">
<form action="{{ route('admin.post.update',$post->id) }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
{{ method_field('patch') }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ $post->title }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select class="js-example-basic-single form-control" name="tags[]" id="tags" multiple="multiple">
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ $post->body }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option <?php if ($cat->id == $post->category_id) {
echo 'selected';
} ?> value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary btn-block">Edit</button>
</form>
</div>
here:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}</option>
#endforeach
</select>
</div>
how can I pass selected post tags from database and show theme here and edit them.
I am using select2 plugin
In select2 I should pass data in jQuery:
$('.js-example-basic-single').select2().val({{ json_decode($post->tags()->getRelatedIds()) }}).trigger('change');
but it doesnt work :(
and I get this error
Method Illuminate\Database\Query\Builder::getRelatedIds does not exist. (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\post\edit.blade.php
Please help me, Thanks!
You have put the code in wrong place:
Try this:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}" {{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $name }}</option>
#endforeach
</select>
</div>

Resources