So I am trying to upload images for a project where each image can have its own description or caption. I am trying to do this through the project creation form. Now, everything works except that I am getting duplicate entries in the project_images table because of the nested foreach loop, take a look at the summarised structure of the code Please, specifically the logic in the storProject method if anyone can help I will be forever grateful. Thank you.
I am using Laravel with Livewire.
Models
Project Model
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->integer('budget');
$table->string('proposed_by');
$table->string('executed_by');
$table->string('status')->nullable();
$table->integer('progress_indicator')->nullable();
$table->date('starting_date');
$table->date('completion_date')->nullable();
$table->string('cover_image')->nullable();
$table->mediumText('body')->nullable();
$table->timestamps();
});
}
Project_images Model
public function up()
{
Schema::create('project_images', function (Blueprint $table) {
$table->id();
$table->string('images');
$table->string('caption')->nullable();
$table->UnsignedBigInteger('project_id');
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->timestamps();
});
}
The Form
<x-slot name="content">
<x-errors />
<div class="space-y-8 divide-y divide-gray-200 mt-10">
<form method="#" enctype="multipart/form-data">
#if ($projectImages)
Images Preview:
<div class="flex flex-row m-8 ">
#foreach ($projectImages as $key => $projectImage)
<div class="flex flex-col gap-3">
<img width="100%" src="{{ $projectImage->temporaryUrl() }}">
<x-input placeholder="Caption"
wire:model.defer="captions.{{ $key }}" />
</div>
#endforeach
</div>
#endif
</div>
<label class="inline-block mb-2 text-gray-500">Upload
Projects Images</label>
<div class="flex items-center justify-center w-full">
<label
class="flex flex-col w-full h-32 border-2 border-dashed hover:bg-gray-500 hover:border-gray-300">
<div class="flex flex-col items-center justify-center pt-7">
<p class="pt-1 text-sm tracking-wider text-gray-400 group-hover:text-gray-600">
Select a photo</p>
</div>
<input wire:model="projectImages" type="file" multiple class="opacity-0" />
</label>
</div>
<x-textarea wire:model.lazy="body" label="Body" placeholder="write your article" />
</form>
</div>
</x-slot>
<x-slot name="footer">
#if ($projectId)
<div class="flex items-center gap-x-3 justify-end">
<x-button wire:click="CancelConfirmation" label="Cancel" flat />
<x-button type="submit" wire:click="updateProject" label="Update" wire:loading.attr="disabled"
primary />
</div>
#else
<div class="flex items-center gap-x-3 justify-end">
<x-button wire:click="CancelConfirmation" label="Cancel" flat />
<x-button type="submit" wire:click="storeProject" label="Create" wire:loading.attr="disabled"
primary />
</div>
#endif
</x-slot>
</x-jet-dialog-modal>
The Project Component
public function storeProject()
{
$this->validate([
'title' => 'required',
'status' => 'required',
'budget' => 'required',
'proposedBy' => 'required',
'executedBy' => 'required',
'startingDate' => 'required',
'completionDate' => 'required',
'progressIndicator' => 'required',
'body' => 'required',
'image' => 'image|max:1024|nullable'
]);
$image_name = $this->image->getClientOriginalName();
$this->image->storeAs('public/photos', $image_name);
$project = new Project();
$project->user_id = auth()->user()->id;
$project->title = $this->title;
$project->status = $this->status;
$project->budget = $this->budget;
$project->proposed_by = $this->proposedBy;
$project->executed_by = $this->executedBy;
$project->starting_date = Carbon::create($this->startingDate);
$project->completion_date = Carbon::create($this->completionDate);
$project->progress_indicator = $this->progressIndicator;
$project->body = $this->body;
$project->cover_image = $image_name;
$project->save();
foreach ($this->projectImages as $projectImage) {
$image_name = $projectImage->getClientOriginalName();
$projectImage->storeAs('public/photos', $image_name);
foreach ($this->captions as $caption) {
$projectImages = new ProjectImages();
$projectImages->project_id = $project->id;
$projectImages->images = $image_name;
$projectImages->caption = $caption;
$projectImages->save();
}
}
$this->notification()->success(
$title = 'Success',
$description = 'Project Created Successfully'
);
$this->reset();
}
so just so you can see visually what am trying to do here is a screenshot of the form
I assume that you only want each project image to have one caption. If that's the case then the nested foreach loops are unnecessary and changing it to one foreach like this should solve the problem.
foreach ($this->projectImages as $key => $value) {
$image_name = $value->getClientOriginalName();
$value->storeAs('public/photos', $image_name);
$projectImages = new ProjectImages();
$projectImages->project_id = $project->id;
$projectImages->images = $image_name;
$projectImages->caption = $this->captions[$key];
$projectImages->save();
}
Related
When I want to delete a comment from a photo, the id is sent by parameter but the delete () function that deletes that record receives the same $ id as null.
First my route
Route::get('/comment/delete/{id}', [App\Http\Controllers\CommentController::class, 'delete'])->name('comment.delete');
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function images()
{
return $this->belongsTo(Image::class, 'image_id');
}
}
CommentController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function save(Request $request){
//Validacion
$validate = $this->validate($request, [
'image_id' => 'required|integer',
'content' => 'string|required'
]);
//Recoger datos
$user = \Auth::user();
$content = $request->input('content');
$image_id = $request->input('image_id');
//Asigno los valores a mi objeto
$comment = new Comment;
$comment->user_id = $user->id;
$comment->image_id = $image_id;
$comment->content = $content;
//guardar en la base de datos
$comment->save();
return redirect()->route('image.detail', [
'id' => $image_id
])->with([
'message' => 'Haz hecho un comentario'
]);
}
public function delete($id){
//Conseguir datos del usuario identificado
$user = \Auth::user();
//Conseguir objeto del comentario
$comment = Comment::find($id);
dd($comment);
//Comprobar si soy el dueƱo del comentario o de la publicacion
if ($user && ($comment->users_id == $user->id || $comment->images_id->users_id == $user->id)) {
$comment->delete();
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario eliminado'
]);
}else{
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario NO eliminado!'
]);
}
}
}
View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
#include('includes.message')
<div class="card pub_image pub_image_detail">
<div class="card-header">
#if($image->user->image)
<div class="container-avatar">
<img src="{{route('user.avatar', ['filename' => $image->user->image])}}" class="avatar">
</div>
#endif
<div class="data-user">
{{$image->user->name.' '.$image->user->surname}}
<span class="nickname">
{{' | #'.$image->user->nick}}
</span>
</div>
</div>
<div class="card-body">
<div class="image-container">
<img src="{{ route('image.file', ['filename' => $image->imagen_path]) }}" alt=""/>
</div>
<div class="description">
<span class="nickname">{{'#'.$image->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($image->created_at)}}</span>
<p>{{$image->description}}</p>
</div>
<div class="likes">
<img src="{{asset('/img/corazon-negro.png')}}" alt=""/>
</div>
<div class="clearfix"></div>
<div class="comments">
<h4>Comentarios ({{count($image->comments)}})</h4>
<hr>
<form action="{{route('comment.save')}}" method="POST">
#csrf
<input type="hidden" name="image_id" value="{{$image->id}}">
<p>
<textarea name="content" id="" cols="30" rows="10" class="form-control box-comment {{$errors->has('content') ? 'is-invalid' : ''}}"></textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</p>
<button type="submit" class="btn btn-success">
Enviar
</button>
</form>
#foreach($image->comments as $comment)
<div class="comment">
<span class="nickname">{{'#'.$comment->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($comment->created_at)}}</span>
<p>{{$comment->content}}</p>
#if(Auth::check() && ($comment->user->id == Auth::user()->id || $comment->images->users_id == Auth::user()->id))
<a href="{{route('comment.delete', ['id', $comment->id])}}" class="btn btn-sm btn-danger">
Eliminar
</a>
#endif
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
I would like to know how I can make the delete button correctly send the id by parameter to the controller, that it receives it and then removes the comment.
Thanks!
Your issue is not defining the id correctly in the array :
{{ route('comment.delete', ['id', $comment->id]) }}
It should be like this:
{{ route('comment.delete', ['id' => $comment->id]) }}
I have a CRUD app with cars and for every car I have fields to create a car and images to upload. Everithing is ok, I have one to many relationship and for a car I can have multiple images . When I create a car and I upload photos these photos are stored correctly in database and in my public/images director. The problem is when I want to make the UPDATE par, I don't know how to update the photos in database.
Here is my code, I have update function where I don't know exactly how to make the update .
My cars table:
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->string('model');
$table->integer('seats');
$table->string('fuel');
$table->integer('year');
$table->string('color');
$table->string('gearbox');
$table->integer('price');
$table->string('coinType');
$table->timestamps();
});
My images table
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('car_id');
$table->string('file_name');
$table->timestamps();
});
My Car model:
class Car extends Model
{
protected $fillable = [
'model',
'seats',
'fuel',
'year',
'color',
'gearbox',
'price',
'coinType',
];
public function images()
{
return $this->hasMany(Image::class);
}
use HasFactory;
}
My Image model:
class Image extends Model
{
protected $fillable = [
'car_id',
'file_name'
];
public function car()
{
return $this->belongsTo(Car::class);
}
use HasFactory;
}
My edit.blade:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h2 class="display-3">Edit a car</h2>
<div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div><br />
#endif
<form method="post" action="{{ url('cars/'. $res->id) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<legend>
<label for="model" class="col-form-label">Model :</label>
<input type="text" class="form-control" id="model" name="model" value="{{ $res->model }}">
</legend>
</div>
<div class="form-group ">
<legend>
<label for="seats" class="col-form-label">Seats :</label>
</legend>
<select name="seats" id="seats" value="{{ $res->seats }}">
<option value="2">2</option>
<option value="4" selected="selected">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="fuel" class="col-form-label">Fuel :</label>
</legend>
<select name="fuel" id="fuel" value="{{ $res->fuel }}">
<option value="benzine+gpl">benzine+gpl</option>
<option value="gpl" selected="selected">diesel</option>
<option value="diesel">gpl</option>
<option value="diesel+gpl">diesel+gpl</option>
<option value="benzine">benzine</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="year" class="col-form-label">Year :</label>
</legend>
<input type="text" name="year" id="year" value="{{ $res->year }}">
</div>
<div class="form-group">
<legend>
<label for="color" class="col-form-label">Color :</label>
</legend>
<input type="text" class="form-control" id="color" name="color" value="{{ $res->color }}">
</div>
<div class="form-group ">
<legend>
<label for="gearbox" class="col-form-label">Gearbox :</label>
</legend>
<select name="gearbox" id="gearbox" value="{{ $res->gearbox }}">
<option value="manual">manual</option>
<option value="automatic" selected="selected">automatic</option>
<option value="semiautomatic">semiautomatic</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="price" class="col-form-label">Price :</label>
</legend>
<input type="text" class="form-control" id="price" name="price" value="{{ $res->price }}">
</div>
<div class="form-group ">
<legend>
<label for="coinType" class="col-form-label">CoinType :</label>
</legend>
<select name="coinType" id="coinType" value="{{ $res->coinType }}">
<option value="EUR">EUR</option>
<option value="LEI" selected="selected">LEI</option>
<option value="USD">USD</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="image" class="col-form-label">Upload images :</label>
</legend>
<input type="file" class="form-control" name="images[]" multiple />
</div>
<hr style="height:2px;border-width:0;color:gray;background-color:gray">
<div class="col-xs-12 col-sm-12 col-md-12 ">
<button type="submit" class="btn btn-primary">Add car</button>
<a class="btn btn-primary" href="{{ route('cars.index') }}"> Back</a>
</div>
</div>
</form>
#endsection
My Controller:
public function store(Request $request)
{
$request->validate([
'model' => 'required',
'year' => 'required',
'color' => 'required',
'price'=> 'required',
'file_name.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$destionationPath = public_path('/images');
$images = [];
$car = new Car();
$car->model = $request->model;
$car->seats = $request->seats;
$car->fuel = $request->fuel;
$car->year = $request->year;
$car->color = $request->color;
$car->gearbox = $request->gearbox;
$car->price = $request->price;
$car->coinType = $request->coinType;
$car->save();
if ($files = $request->file('images')) {
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
}
foreach ($images as $imag) {
$image = new Image();
$image->car_id = $car->id;
$image->file_name = $imag;
$image->save();
}
return redirect()->route('cars.index')->with('success', 'Car saved !');
}
public function update(Request $request, $id)
{
$request->validate([
'model' => 'required',
'year' => 'required',
'color' => 'required',
'price'=> 'required',
'file_name.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$destionationPath = public_path('/images');
$images = [];
$car = Car::find($id);
$car->model = $request->model;
$car->seats = $request->seats;
$car->fuel = $request->fuel;
$car->year = $request->year;
$car->color = $request->color;
$car->gearbox = $request->gearbox;
$car->price = $request->price;
$car->coinType = $request->coinType;
$car->update();
if ($files = $request->file('images')) {
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
}
foreach ($images as $imag) {
//here I don't know what to do
}
return redirect()->route('cars.index')->with('success', 'Car updated !');
}
Thank you.
Looking at your blade file, you don't really show the original images, so the user can't update the images, he can insert new images and the old ones should be deleted, right?
If you want to update the image, you have to show the original images on the blade file with it's ID, so in the backend you can find the image based on the ID
But this should work for you now:
you can just check if the user uploaded any file
if ($files = $request->files('images')) {
...
delete all the old images
$car->images->each(function($image) {
// You probabily should be using Storage facade for this
// this should be the full path, I didn't test it, but if you need add extra methods so it returns the full path to the file
if (file_exists($destionationPath . '/' . $image->file_name) {
unset($destionationPath . '/' . $image->file_name);
}
$image->delete();
});
And then recreate the images like you do on store
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
foreach ($images as $imag) {
$image = new Image();
$image->car_id = $car->id;
$image->file_name = $imag;
$image->save();
}
Using Laravel-5.8, I have been able to save the data into the database including the check box field.
protected $fillable = [
'appraisal_name',
'is_current',
'appraisal_start',
'appraisal_end',
];
public function rules()
{
return [
'appraisal_name' => 'required|min:5|max:100',
'appraisal_start' => 'required',
'appraisal_end' => 'required|after_or_equal:appraisal_start',
'is_current' => 'nullable|boolean',
];
}
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
create.blade
<form action="{{route('appraisal.appraisal_identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
edit.blade
<form action="{{route('appraisal.appraisal_identities.update', ['id'=>$identity->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
I have these issues while trying to update the data?
The edit checkbox field (is_current) did not pick the value from the database when loaded. It remains unchecked.
is_current is either 0 or 1. The goal is that, there can only be one is_current field that is set to 1 in the table. From the checkbox, when is_current is checked to 1, it should set any other is_current that is 1 to 0 in the table.
How do I resolve these issues?
Thank you.
In edit blade update your checkbox code as this:
<input type="checkbox" class="form-control" name="is_current" #if($identity->is_current == 1) checked #endif value="{{old('is_current')}}">
In your update function change this:
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
In your store function change this:
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
try this in the edit blade
<
is_current == 1 ? checked : value="{{old('is_current')}}">
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.
i am new to laravel and i want to ask how to display multiple images that is located in the database.
i have already inserted images in my database through this code
here is my try.blade.php.
<h3>Upload Image</h3>
<form name="form" action="imageupload" method="POST" enctype="multipart/form-
data">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="file" name="img[]" multiple="true">
<br><br>
<input type="submit" name="ok" value="Upload">
</form>
#if(Session::has('msg'))
{{ Session::get('msg')}}
#endif
and here is my web.php
Route::get('imageup','userLog#imageup');
Route::post('imageupload','userLog#imageupup');
and here is my controller
public function imageup(){
return view('try');
}
public function imageupup(Request $request){
if($request->hasFile('img')){
$image_array = $request->file('img');
$array_len = count($image_array);
for($i=0; $i<$array_len; $i++){
$image_size = $image_array[$i]->getClientSize();
$image_ext = $image_array[$i]->getClientOriginalExtension();
$new_image_name = rand(1234,9999).".".$image_ext;
$destination_path = public_path('/images');
$image_array[$i]->move($destination_path,$new_image_name);
$tab = new Tab1;
$tab->image_size = $image_size;
$tab->image_name = $new_image_name;
$tab->save();
}
return back()->with('msg','Images Uploade Successfully');
}
else{
return back()->with('msg','Please choose any image file');
}
}
this is the code in my table
Schema::create('tab1s', function (Blueprint $table) {
$table->increments('id');
$table->string('image_name');
$table->string('image_size');
$table->timestamps();
});
i hope someone can help me.
#foreach(json_decode($posts->images, true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
<a href="{{ URL::to('img/offers/'.$images)}}"
class="portfolio-box">
<img src="{{ URL::to('img/offers/'.$images)}}"
class="img-responsive" alt="--">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<span class="glyphicon glyphicon-zoom-in"
style="font-size: 80px"></span>
</div>
</div>
</a>
</div>
#endforeach