Laravel Update DB with array from views - laravel

i'm doing a simple project but having some difficulties with updating my database with values that I get from a form. The project is having a list of movies and when you click on one it would take you to a page with more details. Theres a button which you can update the details of that movie. I'm trying save whatever details are made to the relevant index of the table using the id. I can't seem to get it to work though. I did something similar when creating a new entry but having some difficulty updating the values of a specific movie/page. Thanks for any help!
Route:
Route::get('catalog', 'App\Http\Controllers\CatalogController#getIndex');
Route::get('catalog/show/{id}', 'App\Http\Controllers\CatalogController#getShow');
Route::get('catalog/create', 'App\Http\Controllers\CatalogController#getCreate');
Route::get('catalog/edit/{id}', 'App\Http\Controllers\CatalogController#getEdit');
Route::post('catalog/create', 'App\Http\Controllers\CatalogController#postCreate');
Route::put('catalog/edit/{id}','App\Http\Controllers\CatalogController#putEdit');
Controller:
public function getEdit($id)
{
return view('catalog.edit', ['arrayPeliculas' => Movie::all()]);
}
public function getCreate()
{
return view('catalog.create');
}
public function postCreate(Request $request)
{
$Movie = new Movie;
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
public function putEdit(Request $request, $id)
{
$Movie = new Movie;
$Movie[$id]->title = $request->title;
$Movie[$id]->year = $request->year;
$Movie[$id]->director = $request->director;
$Movie[$id]->poster = $request->poster;
$Movie[$id]->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Edit page:
<form method="PUT">
{{ method_field('PUT') }}
{{-- TODO: Protección contra CSRF --}}
{{ csrf_field() }}
<div class="form-group">
<label for="modificar">Modificar Pelicula</label>
<input type="text" name="title" id="title" class="form-control" value="{{ $arrayPeliculas[$id]->title }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el año --}}
<label for="Año">Año</label>
<input type="text" name="year" id="year" class="form-control" value="{{ $arrayPeliculas[$id]->year }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el director --}}
<label for="Director">Director</label>
<input type="text" name="director" id="directo" class="form-control" value="{{ $arrayPeliculas[$id]->director }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el poster --}}
<label for="Poster">Poster</label>
<input type="text" name="poster" id="poster" class="form-control" value="{{ $arrayPeliculas[$id]->poster }}">
</div>
<div class="form-group">
<label for="synopsis">Resumen</label>
<textarea name="synopsis" id="synopsis" class="form-control" rows="3" >{{ $arrayPeliculas[$id]->synopsis }}"</textarea>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" style="padding:8px 100px;margin-top:25px;">
Añadir película
</button>
</div>
</form>
I tried a few other things like->update but I can't seem to get it to work properly.

To update an existing model, first find() it.
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Using the update function should also work then:
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->update([
'title' => $request->title,
'year' => $request->year,
'director' => $request->director,
'poster' => $request->poster,
'synopsis' => $request->synopsis,
]);
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
You could really simplify it with some Laravel magic like Route Model Binding...
Route::put('catalog/edit/{movie}','App\Http\Controllers\CatalogController#putEdit');
...
public function putEdit(Request $request, Movie $movie)
{
$movie->update($request->all());
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}

Related

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?
Route
Route::post('/store/{product}', 'AttachmentController#store')->name('attachment.store');
Product Model
public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
Attachment Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Controller
public function create()
{
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {
$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
Blade View
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
#csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div>
</div>
</form>
You have to use form action like below
<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

I got this error "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type

When i try to insert data into my table this error occurs
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\Portal\vendor\laravel\framew...
view
<form method="post" action="{{ route('notice.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="Select Group to Post Notice">Select Group to Post Notice </label>
<select class="bg-white text-danger form-control " name='GroupID[]' multiple>
#foreach ($users as $user)
<option value="{{ $user->GroupID }}">{{ $user->GroupID }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Enter Notice">Enter Notice</label>
<input class="bg-white text-danger p-2 form-control form-control-sm" type="text" name="Notice" placeholder="Enter Notice">
</div>
<input class="btn btn-danger btn-lg px-5" type="submit" name="submit">
</form>
controller
public function store(Request $request)
{
$member = $request->input('GroupID');
foreach($member as $value) {
$storeInfo = new notice();
$storeInfo->GroupID = $request->input('GroupID');
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}
I would imagine the reason you're getting this error is because of:
$storeInfo->GroupID = $request->input('GroupID');
$request->input('GroupID') will return an array (name='GroupID[]') and not an individual id.
Since you're already looping through the group ids you can instead use the value for the GroupId:
public function store(Request $request)
{
foreach ($request->input('GroupID') as $groupId) {
$storeInfo = new notice();
$storeInfo->GroupID = $groupId; //<--here
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('notice');
}
try changing controller logic
public function store(Request $request)
{
//
$member=$request->input('GroupID');
foreach($member as $value){
$storeInfo = new notice();
$storeInfo->GroupID = $value;
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}

I want to display data in textfield. when search data have

I want to display data in textfield . Not all data. When search by name and it have data then went to display data in textfield. And search form and want to display form is same form.
<form action="postAuth" method="post" enctype="multipart/form-data">
<div class="input-group">
<input type="text" class="form-control" name="productname" placeholder="Search Product"> <span class="input-group-btn">
<button type="submit" class="btn btn-default" name="search">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<div class="form-group">
<label for="ProductName" >Product Name :</label>
<input type="text" class="form-control" name="ProductName">
</div>
</form>
route
Route::post("postAuth", ['as' => 'search' , 'uses'=> 'ProductController#postAuth']);
That's my controller
public function postAuth(Request $request)
{
//check submit
$update = $request->get('update',false);
if($update){
return $this->update($request);
}
$productname = $request->input('productname');
$product = DB::table('products')
->where('product_name','LIKE','%'.$productname.'%')
->get();
if($product->count() > 0)
return redirect()->to('/update')->withDetails($product)->withQuery($productname);
else
$request->session()->flash('alert-danger','No Data Found!');
return redirect()->to('/update');
}
can anyone help me please
Here what you exactly want : Just for example
<div class="form-group">
{{Form::label('name', trans('admin.venue.fields.name'),['class' => 'col-md-4 control-label'])}}
<div class="col-md-6">
{{Form::text('name',old('name', isset($venue) ? $venue->name : ''),['class' => 'form-control'])}}
</div>
</div>
Model function example :
public function save(Request $request) {
try {
$this->validate($request, Venue::rules(), Venue::messages());
$venue = Venue::saveOrUpdate($request);
if($venue !== false) {
if($request->get('continue', false)) {
return redirect()->route('admin.venue.edit', ['id' => $venue->id])->with('success', trans('admin.venue.save_success'));
} else {
return redirect()->route('admin.venue.index')->with('success', trans('admin.venue.save_success'));
}
} else {
return back()->with('error', "Unable to save venue")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save venue")->withInput();
}
}
Hope it is useful.
use session() in the value field of ProductName input tag and with some logic, for example
view file:
#if(session()->has('data'))
#if(count(session('data')))
#foreach(session('data') as $data)
<input type="text" class="form-control" name="ProductName" value="{{ $data->prodcut_name }}">
#endforeach
#else
<input type="text" class="form-control" name="ProductName" value="No Data Available">
#endif
#else
<input type="text" class="form-control" name="ProductName">
#endif
and in Controller:
public function postAuth(Request $request) {
$productname = $request->input(productname);
$product_search = Products::where('product_name', $productname)->get();
if($product_search) {
return redirect()->back()->with('data', $product_search);
}
}

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Resources