How to display selected tags in select option value in laravel? - 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>

Related

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 Request Input is not usable data

Ok maybe this is a noob laravel question but when I'm trying to store data from a form I used a $request->input in a query to get a needed field for insert but the query will not run. Note: does run if I just set something like $project_id = 6.
public function store(Request $request)
{
$project_id = $request->input('project_id');
$company = Project::where('id', $project_id)->first();
if(Auth::check()){
$task = Task::create([
'name' => $request->input('name'),
'project_id' => $project_id,
'company_id' => $company->id,
'days' => $request->input('days'),
'hours' => $request->input('hours'),
'user_id' => Auth::user()->id
]);
if($task){
return redirect()->route('tasks.index')
->with('success' , 'Task created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new task');
}
Note:
I've tried a couple different things I've found online like $project_id = $request->project_id or $project_id = $request['project_id']
Is request->input just used for inserts and can't be used as a normal varible?
Update: here is the create.blade form it's coming from
#extends('layouts.app')
#section('content')
<div class="row col-md-9 col-lg-9 col-sm-9 pull-left " >
<h1>Add a Task </h1>
<!-- Example row of columns -->
<div class="col-md-12 col-lg-12 col-sm-12" style="background: white; margin: 10px;" >
<form method="post" action="{{ route('tasks.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="project-name">Name<span class="required">*</span></label>
<input placeholder="Enter name"
id="project-name"
required
name="name"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-days">Days Taken<span class="required"></span></label>
<input
id="task-days"
required
name="days"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-hours">Hours Taken<span class="required"></span></label>
<input
id="task-hours"
required
name="hours"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<input
class="form-control"
type="hidden"
name="project_id"
value="{{ $project_id }}"
/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{$project_id}}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit"/>
</div>
</form>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 col-sm-3 pull-right">
<div class="sidebar-module sidebar-module-inset">
<h4>Actions</h4>
<ol class="list-unstyled">
<li>All tasks</li>
</ol>
</div>
</div>
#endsection
Let's examine your <form> below:
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project_id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
In this code, you have a hidden input with the name "project_id", and if $projects is not null, you also have a select with the name "project_id". Having multiple elements with the same name is invalid, and can cause issues.
Secondly, in this line:
<option value="{{ $project_id }}">{{ $project->name }}</option>
$project_id is the same value you have in the hidden input above. When you're looping over $projects, this should be $project->id:
<option value="{{ $project->id }}">{{ $project->name }}</option>
Lastly, make sure that $project_id is a valid value if you're going to send it, and consider adjusting your logic to only send the hidden input if $projects is null:
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#else
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#endif
With all that adjusted, you should be able to retrieve the expected value with $request->input("project_id")

Laravel save related data in database

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() !!}

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

when click submit error is occur

when click on submit data,data successfully save and show in database but got error in index page, i think don't get it user-id
Trying to get property 'id' of non-object (View:
C:\xampp\htdocs\ytl\resources\views\profile\index.blade.php)
This is index.blade.php file
<form method="post", id="form", action="{{action('Profile\UserProfileController#index')}}" accept-charset="UTF-8">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6 mb-3 form-group">
Exchange:<select name="exchange_id" id="exchange" class="form-control " onchange="myfunc()">
<option value="">Select</option>
#foreach($exchanges as $key=>$val )
<option value="{{ $val->id }}">{{ $val->exchange }}</option>
#endforeach
</select>
{{--{!! Form::label('exchange_id', 'Exchanges: ') !!}--}}
{{--{!! Form::select('exchange_id', ['' => 'Choose Options'] + $exchanges, null, ['class' => 'form-control', 'id' => 'exchange', 'name' => 'exchange_id'])!!}--}}
</div>
<div class="col-md-6 mb-3 form-group">
Market<select name="market_id" id="market" class="form-control bindselect" >
<option value="">Select</option>
{{--#foreach($markets as $key=>$val )--}}
{{--<option value="{{ $val->id }}">{{ $val->market }}</option>--}}
{{--#endforeach--}}
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Country:<select name="country_id" id="country" class="form-control " >
<option value="">Select</option>
#foreach($countries as $key=>$val )
<option value="{{ $val->id }}">{{ $val->country }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Company:<select name="brokerage_company_id" id="brokerage_company_id" class="form-control " >
<option value="">Select</option>
#foreach($brokerage_company as $key=>$val )
<option value="{{ $val->id }}">{{ $val->brokerage_company }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
{{--{!! Form::label('Intraday_Charge', 'Intraday Charge:') !!}--}}
{{--{!! Form::text('Intraday_Charge', null, ['required' => 'required', 'class'=>'form-control number_only'])!!}--}}
Intraday_charge: <input type="text" name="charge_intraday" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_delivery" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_lot" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_order" class="form-control"><br>
</div>
<div class="mb-3 form-group">
{{--{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}--}}
<input type="submit" value="Submit">
</div>
</div>
</form>
This is controller in which 2 method. 1st index and 2nd store method
public function index(Request $request){
$exchanges = Exchange::select('exchange','id')->get();
$markets = Market::select('market','id')->get();
$countries = Country::select('country','id')->get();
$brokerage_company = BrokerageCompany::select('brokerage_company','id')->get();
return view('profile.index', compact( 'exchanges','markets','countries','brokerage_company'));
}
public function store(Request $request){
$Input = $request->all();
$user = Auth::user();
$user->userprofile()->create($Input);
$user_id = Auth::user()->id;
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$countries = Country::pluck('country','id')->all();
$brokerage = BrokerageCompany::pluck('brokerage_company','id')->all();
$user_profile = UserProfile::pluck('charge_intraday','charge_delivery','charge_per_lot','charge_per_order');
return view('profile.index', compact( 'exchanges','markets','countries','brokerage','user_profile'));
}
Since Laravel 5.2 pluck() method of Eloquent builder returns a collection of values from given column. When you call all() on this collection, you simply get an array of values from that first column. For example, when you call
$exchanges = Exchange::pluck('exchange','id')->all();
$exchanges will be an array that contains all values of exchange column in your Exchanges table. Hence the error, as you're trying to access id attribute of this scalar value.
I guess you're trying to limit number of columns fetched from the database. Call select() method instead of pluck():
$exchanges = Exchange::select('exchange','id')->get();

Resources