How to update an array field in laravel? - laravel

EDIT FORM
<div class="form-group mb-3">
<label>Country:</label>
<div class="col-sm-4">
<select id="country-dd" name="country[]" class="js-example-basic-multiple form-control" multiple="multiple">
#foreach($countries as $country)
<option value="{{$country->id }}" {{in_array($country->id, explode(',',$user->country)) ? 'selected' : '' }}> {{$country->name}}</option>
#endforeach
</select>
</div>
</div>
CONTROLLER
public function updateuser(Request $request, $id)
{
// dd($request->all());
$request->validate([
'name'=>'required',
'email'=>'required|email|unique:users',
'country'=>'required',
'state'=>'required',
'city'=>'required',
'role_id'=>'required'
]);
$name = $request->name;
$email=$request->email;
$country=implode(',',$request->country);
$state=implode(',',$request->state);
$city=implode(',',$request->city);
$role_id=$request->role_id;
User::whereId($id)->update($request->all());
return redirect()->route('viewuser');
}
ROUTE
Route::put('/updateuser/{id}',[UserController::class,'updateuser'])->name('updateuser');
If I update a record. It just reloads the page and there is no error. Please correct me if I am doing wrong. Thanks in advance.

Try in the CONTROLLER:
public function updateuser(Request $request, $id)
{
$request->validate([
'name'=>'required',
'email'=>'required|email|unique:users',
'country'=>'required',
'state'=>'required',
'city'=>'required',
'role_id'=>'required'
]);
$user = User::findOrFail($id);
$user->name = $request->name;
$user->email=$request->email;
$user->country=implode(',',$request->country);
$user->state=implode(',',$request->state);
$user->city=implode(',',$request->city);
$user->role_id=$request->role_id;
$user->update();
return redirect()->route('viewuser');
}
Try in the form:
<form action="{{ route('updateuser',$data->id) }}" method="POST" enctype="multipart/form-data">
#method('PUT')
#csrf
ALL YOUR INPUTS HERE
<div class="card-footer">
<button type="submit" class="btn btn-primary mt-1 pr-4 pl-4">Update</button>
</div>
</form>
Route
Route::match(['put', 'patch'], 'updateuser/{id}', [UserController::class,'updateuser'])->name('updateuser');

Related

Livewire: problem whit display data and form

I have problem with display data and form on one page.
Display data from database disappear after write in textarea any word. The same problem ist when i click on submit. In debugger is only data from first query, from second is cleared.
I try with one query (second), but it's the same.
My example code
route web:
Route::middleware(['auth:sanctum', 'verified'])->get('/tickets/show/{slug}', Tickets\Show::class)->name('tickets.show');
Livewire:
public $ticket;
public $slug;
public $posts;
public $content_post;
public $ticket_id;
public function mount($slug){
$this->ticket = Tickets::where('tickets.id','=', $slug)->join('users', 'users.id', '=', 'tickets.user_id')
->select('users.email','users.phone','users.username','users.first_name','users.last_name','tickets.user_id','tickets.created_at',
'tickets.id', 'tickets.subject','tickets.status_id','tickets.admin_id')->first();
$this->posts = TicketsPost::where('tickets_posts.ticket_id','=', $slug)->join('users', 'users.id', '=', 'tickets_posts.user_id')
->select('users.email','users.username','users.first_name','users.last_name','tickets_posts.user_id','tickets_posts.created_at',
'tickets_posts.ticket_id','tickets_posts.post')->get();
}
public function addPost()
{
$this->validate([
'content_post' => 'required'
]);
$user_id = Auth::user()->getAuthIdentifier();
TicketsPost::create([
'ticket_id' => $this->ticket_id,
'user_id' => $user_id,
'post' => $this->content_post,
]);
}
public function render()
{
return view('livewire.tickets.show');
}
View:
<p >#{{$ticket->id}}</p>
<p >{{$ticket->subject}}</p>
#foreach($posts as $post)
<p >{{$post->first_name}} {{$post->last_name}}</p>
<p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p>
<p > {{$post->post}}</p>
#endforeach
<form >
<input type="hidden" name="ticket_id" value="2" wire:model="ticket_id">
<textarea name="content_post"
class=""
rows="5" required="" placeholder="Treść wiadomości" wire:model="content_post"></textarea>
#error('content_post') <span class="text-red-500">{{ $message }}</span>#enderror
<button wire:click.prevent="addPost()" type="submit" class="">
<span id="btn_text" class="ml-2">Dodaj</span>
</button>
</form>
In Livewire, make sure your component has a single-level root element only.
And, don't forget to add wire:key in your element inside every loop in a blade.
Your loop should be as;
#foreach($posts as $key => $post)
<div wire:key="{{'post'.$key}}">
<p>{{$post->first_name}} {{$post->last_name}}</p>
<p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p>
<p > {{$post->post}}</p>
</div>
#endforeach

production.ERROR: Undefined variable: id Laravel blade

In my Laravel-5.8 I have this code in the controller:
public function appraisal(Request $request)
{
try {
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$company = OrgCompany::where('id', $userCompany)->first();
$identities = Identity::where('company_id', $userCompany)->pluck('appraisal_name','id');
$goals = AppraisalGoal::where('employee_id', $userId)
->where(function ($query) {
$query->where('is_approved', 3)->orWhere('is_visible', 0);
})
->whereNull('deleted_at')
->orderBy('goal_type_id');
$method = $request->method();
if ($request->isMethod('post')) {
$id = $request->input('identity_id');
if ($request->has('search')) {
// select search
if ($request->input('identity_id')) {
$goals->where('identity_id',$request->input('identity_id'));
}
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
} elseif ($request->has('viewIdentity')) {
// select goal identity
if ($request->input('identity_id')) {
return view('performance_dashboard', $id);
}
}
} else {
//select current year
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
}
} catch (Exception $exception) {
Log::error($exception);
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
view blade: appraisal-default
<div class="row" style="margin-bottom: 10px">
<label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
<div class="col-sm-8">
<select id="identity" name="identity_id" class="form-control">
<option value="">--- Select Performance Period ---</option>
#foreach ($identities as $ids => $name)
<option value="{{ $ids }}" {{ request( 'identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
#endforeach
</select>
</div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
</div>
</div>
In the view, I have two buttons with names: search and viewIdentity
When the
<select id="identity" name="identity_id" class="form-control">
is selected.
If search button is submitted, it displays the result on the same page. This is working.
However, where I'm having problem is when viewIdentity button is submitted. At this point it suppose to take the id of the dropdown as the parameter in:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
and display the result in another page: performance_dashboard
I got this error in the view:
production.ERROR: Undefined variable: id
It points to this line in the view:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
How do I get it resolved?
Thanks

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

Undefined variable: posts when passing parameter from controller to view

I'm trying to create a search function in Laravel and its returning me with "undefined variable: posts" when I do foreach on my view.
My code:
Post Model
class Post extends Model {
protected $fillable = [
'creator',
'post_url',
'books',
'likes',
'created_at'
];
public function user() { return $this->belongsTo(User::class); }
}
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search($keyword)
{
$result = Post::where('books', 'LIKE', "'%' . $keyword . '%'")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search/{keyword}', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
What am I doing wrong here?
This might help you out.
Homeview.blade.php
<form action="/search" method="POST">
#csrf // include your csrf token
<input type="text" class="search-text form-control form-control-lg" id="q" name="q" placeholder="Search" required>
</form>
Searchview.blade.php
<!-- or did you return a collection? -->
#if( $posts->count() > 1 )
<!-- then loop through the posts -->
#foreach( $posts as $post )
<div class="post"> {{ $post->id }} </div>
#endforeach
#else
#if( !empty($posts) )
<div class="post"> {{ $post->id }} </div>
#endif
#endif
Routes/web.php
Route::post('/search', 'PostsController#show')->name('posts.show');
PostsController
use App\Post;
public function show( Request $request )
{
$result = Post::where("books", "LIKE", "%{$request->input('q')}%")->get();
// Uncomment the following line to see if you are returning any data
// dd($result);
// Did you return any results?
return view('searchview', ['posts' => $result]);
}
The reason it wasn't working,
Route::get('/search/{keyword}', 'SearchController#search');
In your route file you were looking for a {keyword} that was never passed by the form. Your form action is action="{{ url('/search') }}". A get variable will not be picked up by a route and if it was you called the input 'q' anyway.
So then in your controller you were looking for the keyword being passed that is never passed in.
public function search($keyword)
Instead the correct thing to do is pass in the Request object like so
public function search(Request $request)
Then use $request->input('q') to retrieve the passed value through your form.
In your example $keyword would always have been blank.
Corrected code
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search(Request $request)
{
$result = Post::where('books', 'LIKE', "%{$request->input('q')}%")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
try:
return view('/search')->with('posts', $result);
Or even better with dinamic vars.
return view('/search')->withPosts($result);

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