No error with Fail Save and show 302 post error... How To solve it? - laravel

<div class="row">
<div class="col-md-6">
<h3>Create New Expenses</h3>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form" method="POST" action="{{ route('exp.store') }}" autocomplete="off">
<div class="form-group">
<label>Seller :</label>
<input type="text" name="seller_name" class="form-control" value="{{ old('seller_name',isset($exp) ? $exp->seller_name : '') }}" placeholder="Seller">
</div>
<div class="form-group">
<label>Date :</label>
<input type="date" name="date" class="form-control" value="{{ old('date',isset($exp) ? $exp->date : '') }}">
</div>
<div class="form-group">
<label>Select Type :</label>
<select class="form-control" name="category" value="">
<option value=""> Select Type </option>
<option value="1"{{ isset($exp) ? ($exp->category == 1 ? 'selected' : '') : '' }}> Communication </option>
<option value="2"{{ isset($exp) ? ($exp->category == 2 ? 'selected' : '') : '' }}> Transport </option>
<option value="3"{{ isset($exp) ? ($exp->category == 3 ? 'selected' : '') : '' }}> Tools </option>
<option value="4"{{ isset($exp) ? ($exp->category == 4 ? 'selected' : '') : '' }}> Raw Material </option>
</select>
</div>
<div class="form-group">
<label>Amount(RM) :</label>
<input type="number" name="amount" class="form-control" value="{{ old('amount',isset($exp) ? $exp->amount : '') }}" placeholder="0.00">
</div>
<br>
<button type="submit" class="btn btn-primary btn-sm">Save</button>
<a class="btn btn-danger btn-sm" href="{{ route('exp.index') }}">Cancel</a>
</form>
</div>
</div>
This is my saving data function
public function store(Request $request){
$this->validate($request, [
'seller_name' => 'required|max:50',
'date' => 'required',
'category' => 'required',
'amount' => 'required'
]);
DB::beginTransaction();
try{
$exp = new Exp();
$this->saveData($exp, $request);
DB::commit();
return redirect()->route('exp.index');
} catch (\Exception $ex){
DB::rollback();
return back()->withInput()->withErrors('Fail to save.');
}
}
private function saveData($exp, Request $request){
$exp->seller_name = $request->input('seller_name');
$exp->date = $request->input('date');
$exp->category = $request->input('category');
$exp->amount = $request->input('amount');
$exp->save();
}
This is my Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Exp extends Model
{
protected $table = 'exp';
public $primaryKey = 'exp_id';
}
I'm new using this MVC .... i don't know why cant't saving but all my code look no error.
I try to find it but i find nothing ..
I need some help...
i already provide my view, controller and model
and below is my web.php
Route::get('/exp/create', 'ExpController#create')->name('exp.create');
Route::post('/exp/store', 'ExpController#store')->name('exp.store');
TQ.

Seems like you forgot to add mass assignment fields to your Exp model, hence the fields are not saved in your database. Add all the fields you want to be mass assigned to your model, and it should be working as expected:
protected $fillable = ['field_1', 'field_2', .... 'etc'];
Read more about this on official documentation

Related

Laravel : Call to a member function getClientOriginalName() on null when Update Data

I will update the data its contain image, then when I will send to update here's the error Call to a member function getClientOriginalName()
This is my Controller
public function updateBook(Request $request, $id){
$book = DB::table('books')->where('id',$id);
$old = $book->select('images');
$ChecK = 0;
$file = var_dump($request->file('images')->getClientOriginalName());
$filename = time().$file;
$path = public_path('/Uploads');
if($request->hasFile('images')){
$file = $request->file('images');
$file->move($path, $filename);
Storage::delete($old);
$ChecK = 1;
}
else {
dd('Request Hash No File!');
}
$data = [
'name'=> $request->input('bookName'),
'year'=> $request->input('tahunT'),
'author'=> $request->input('author'),
'summary'=> $request->input('Summary'),
'publisher'=> $request->input('publishers'),
'pageCount' => $request->input('pageCount'),
'readPage'=> $request->input('ReadPage'),
'finished' => '$pageCount' == '$readPage' ? true : false,
'reading' => '$readPage' > 0 ? true : false,
'updatedAt'=> new DateTime()
];
if( $ChecK == 1){
$data = ['images' => $filename];
$book->update($data);
return redirect('home')->with('status', 'update succesfully');
}
else {
$data = ['images' => $old];
$book->update($data);
return redirect('home')->with('status', 'Update with old image ');
}
}
Here is the view
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
#foreach ($toEdit as $dt)
<form class="row g-3" enctype="multipart/form-data" method="POST" action="{{ route('update', $dt->id) }}" value="PUT">
{{ csrf_field() }}
<div class="col-md-6">
<label for="bookName" class="form-label">Nama Buku:</label>
<input type="text" class="form-control" name ="bookName"id="bookName" value="{{ ($dt->name) }}">
</div>
<div class="col-md-3">
<label for="tahunT" class="form-label">Tahun Terbit : </label>
<input type="number" class="form-control" name="tahunT" id="tahunT" value="{{ ($dt->year) }}">
</div>
<div class="col-md-3">
<label for="author" class="form-label">Author : </label>
<input type="text" class="form-control" name="author" id="author" value="{{ ($dt->author) }}">
</div>
<div class="col-md-6">
<label for="publishers" class="form-label">Publisher : </label>
<input type="text" class="form-control" name="publishers" id="publishers" value="{{ ($dt->publisher) }}">
</div>
<div class="col-md-3">
<label for="pageCount" class="form-label">Page Count :</label>
<input type="number" class="form-control" name="pageCount" id="pageCount" value="{{ ($dt->pageCount) }}">
</div>
<div class="col-md-3">
<label for="ReadPage" class="form-label">Read Page :</label>
<input type="number" class="form-control" name="ReadPage" id="ReadPage"value="{{ ($dt->readPage) }}">
</div>
<div class="col-12">
<label for="Summary" class="form-label">Summary :</label>
<textarea class="form-control" name="Summary" id="Summary">{{ ($dt->summary) }}</textarea>
</div>
<div class="col-md-12">
<label for="images" class="form-label">Book Image :</label>
<input type="file" class="form-group" name="images">
<br>
<img src="{{ asset('Uploads/'.$dt->images) }}" widht="300px"/>
<br>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
#endforeach
</div>
Here, I will update the data, if user want to change the images, so the image will be update and if no, the images use the old one. It's rull same as the other input. But, when I try to upload the new one, the error Call to a member function getClientOriginalName() happen.
Do you have any suggestion to this? I already add the code enctype="multipart/form-data" and var_dump() but the error was same. Thank you :)
You have to check, with a condition, if your image is null or not in order to avoid this error.
Try something like :
if ( isset($request->file('images')) != null ) {
$ChecK = 0;
$file = $request->file('images')->getClientOriginalName();
$filename = time().$file;
$path = public_path('/Uploads');
}
//..
Just add a simple condition :
If($request->file('image')) {
...
$request->images->getClientOriginalNe();
.....
}

Using Select in an Edit Form Laravel

Im trying to implement a Edit function to update permissions from an Laravel User, (I already installed Spatie), it parcially works, it save the changes but I cant see the permissions of the role on the Select Form. Any help please
<--CONTROLLER-->
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
return view('admin_roles_edit', compact('role','permissions', 'permissions1'));
}
public function update(Request $request, $id)
{
$request->validate([
'name'=>'required|max:30',
]);
$role = Role::findById($id);
$role->update($request->all());
$role->permissions()->sync($request->permissions);
return redirect()->route('admin.roles.index')->with('message', 'El rol se ha actualizado correctamente');
}
<--HTML-->
<form action="{{route('admin.roles.update', $role->id)}}" method="post"
class="form">
#csrf
<div class="form-group has-feedback">
<label class="control-label col-lg-3">Nombre<span
class="text-danger">*</span></label>
<input type="text" class="form-control" name="name"
value="{{$role->name}}" required="required">
#error('name')
<label class="validation-error-label" for="basic">{{$message}}</label>
#enderror
</div>
<div class="form-group has-feedback">
<label class="control-label col-lg-3">Permisos<span
class="text-danger">*</span></label>
<div class="multi-select-full">
<select class="multiselect" multiple="multiple" name="roles">
#foreach($permissions as $permission)
<option value="{{$permission->id}} #if($permission->id == $role->permission) selected #endif">{{$permission->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group pull-right">
<a href="{{route('admin.roles.index')}}" type="button" class="btn btn-default"><i
class="icon-cross2 position-left"></i>Cancelar
</a>
<button type="submit" class="submit-btn btn btn-success"><i
class="icon-add position-left"></i>Editar
</button>
</div>
</form>
<--RESULT-->
in your controller add this line:
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
$rolePermissions = $role->permissions()->pluck('name','id')->toArray();
return view('admin_roles_edit', compact('role','permissions', 'rolePermissions'));
}
update your blade:
<option value="{{$permission->id}}" {{in_array($permission->id, array_keys($rolePermissions)) ? 'selected' : '')}}>{{$permission->name}}</option>
Fixed finally
RoleController.php
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
return view('admin_roles_edit', compact('role','permissions'));
}
RoleView.blade.php
<select class="multiselect" multiple="multiple" name="roles">
#foreach($permissions as $permission)
<option value="{{$permission->id}}"
#if($role->hasPermissionTo($permission->id))
selected="selected"
#endif/>{{$permission->name}}</option>
#endforeach
</select>
Fixed Result

Laravel - How to display child goal type name on select dropdown on edit form

In my Laravel-5.8 project, I am trying to child name (text) on select list in edit form.
I have this table:
CREATE TABLE `goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Model
class GoalType extends Model
{
public $timestamps = false;
protected $table = 'goal_types';
protected $primaryKey = 'id';
protected $fillable = [
'name',
'parent_id',
'max_score',
];
protected $casts = [];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function parent()
{
return $this->hasOne(App\Models\GoalType::class, 'id', 'parent_id');
}
}
Controller
public function index()
{
$categories = GoalType::with('children')->whereNull('parent_id')->get();
return view('goal_types.index')->with('categories', $categories);
}
public function create()
{
return view('goal_types.create');
}
public function store(StoreGoalTypeRequest $request)
{
$data = GoalType::create([
'name' => $request->name,
'parent_id' => $request->parent_id,
'max_score' => $request->max_score,
]);
Session::flash('success', 'Goal Type is created successfully');
return redirect()->route('goal_types.index');
}
I have a modal form for the edit
view
<div class="row">
<div class="col-md-8">
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Goal Type(s)</h3>
</div>
<div class="card-body">
<ul class="list-group">
#foreach ($categories as $category)
<li class="list-group-item">
#if ($category->children)
<ul class="list-group mt-2">
#foreach ($category->children as $child)
<li class="list-group-item">
<div class="d-flex justify-content-between">
{{ $child->name }}
<div class="button-group d-flex">
#can('goal_type_edit')
<button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $child->id }}" data-name="{{ $child->name }}">Edit</button>
#endcan
</div>
</div>
</li>
#endforeach
</ul>
#endif
</li>
#endforeach
</ul>
</div>
</div>
</div>
<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Goal Type</h4>
<form action="" method="POST">
#csrf
#method('PUT')
<div class="modal-body">
<div class="form-group">
<label class="control-label"> Parent Goal Type:</label>
<select class="form-control select2bs4" data-placeholder="Choose Parent Goal Type" tabindex="1" name="parent_id" style="width: 100%;">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label"> Name:<span style="color:red;">*</span></label>
<input type="text" name="name" class="form-control" value="" placeholder="Category Name" required>
</div>
<div class="form-group">
<label class="control-label"> Max. Weight (%):</label>
<input type="number" name="max_score" class="form-control" value="" step="0.01" placeholder="Enter maximum weight here: 15, 50, 75 etc" style="width: 100%;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
When I click on edit from the index a modal form should popup to display the child name where the parent_id equals the id of the parent as it is in the database. But the select dropdown value/text is not displaying anything until when I click on the select dropdown.
How do I modify
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
in the edit to achieve that (displaying the name of the select child on the dropdown)?
Thanks
In your edit view you must pass your category id in your form action like this action="{{ route('admin.categories.update' , $category->id) }}" and then compare it with parent_id and in your category model you have to pass children.
category model:
public function children()
{
return $this->hasMany(GoalType::class, 'parent_id' , 'id')->with('children');
}
edit.blade.php view
<div class="col-md-12">
<label for="parent_id" class="form-control-label">parents category name</label>
<select class="form-control" data-toggle="select" data-live-search="true" name="parent_id" id="parent_id">
<option value="0" {{ $category->parent_id === 0 ? 'disabled' : '' }} selected> - Default</option>
#foreach(\App\Models\Category::latest()->get() as $cate)
<option value="{{ $cate->id }}" {{ $cate->id === $category->parent_id ? 'selected' : '' }} {{ $cate->id === $category->id ? 'disabled' : '' }} {{ $cate->id === $category->parent_id ? 'disabled' : '' }}>{{ $cate->name }}</option>
#endforeach
</select>
</div>

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();

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