Update 2 tables with 1 form in laravel - laravel

I have users table and profiles table, now i want let users to update their info in single form.
Logic
name & email will update in users table
rest of the fields will update in profiles table
Code
blade (form)
{{ Form::model($user, array('route' => array('profileupdate', $user->id), 'method' => 'PUT','files' => true)) }}
<div class="row">
<div class="col-md-6">
<label for="name">Name</label>
{{Form::text('name', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="email">Email</label>
{{Form::text('email', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="about">About</label>
{{Form::textarea('about', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<div class="row">
<div class="col-md-6">
<label for="phone">Phone</label>
{{Form::text('phone', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="website">Website</label>
{{Form::text('website', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="state">State</label>
{{Form::text('state', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="city">City</label>
{{Form::text('city', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-12 mt-3">
<label for="photo">Photo</label>
{{Form::file('photo', array('class' => 'search-field'))}}
</div>
</div>
</div>
<div class="col-md-12">
{{ Form::submit('Update', array('class' => 'btn btn-success mt-5')) }}
</div>
</div>
{{Form::close()}}
Screenshot (code above)
controller
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
$user->save();
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
PS: please don't go with my controller method, I just put data that
way so you can know what field belongs to what table.
Question
Any idea how i can save my data in 2 tables at the same time?
And I get this Error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

You need to check whether save in both or not
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
if($user->save())
{
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
return redirect()->back()->with('error','Something went wrong');
}
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException this exception comes when you are trying to access post method by hiiting the url in browser.

Since you can't insert into multiple tables in one MySQL command, there is no way to accomplish your requirement. But You can however use a Single Transaction.
DB::transaction(function() {
// first update
User::whereId($id)->update([
'name' => $reqquest->name,
'email' => $request->email,
..........
]);
// second update
Profile::whereId($id)->update([
'about' => $request->website,
'mobile' => $request->mobile,
..........
..........
]);
}

Related

Invalid argument supplied for foreach() in view page getting issue laravel5.5

When trying to update or fetch data on edit page getting bellow issue Invalid argument supplied for foreach() in the Form::select() area.
Below is my controller :
if (!$_POST) {
$bedrooms = ["studio"];
$bedrooms[0] = "Studio";
$i = 1;
while ($i < 10) {
$beds = [];
$i = 1;
while ($i < 16) {
$bathrooms = [];
$bathrooms[0] = 0;
$i = 0;
while ($i < 8) {
$accommodates = [];
$i = 1;
while ($i < 16) {
$data["bedrooms"] = ["studio"];
$data["beds"] = [1,2,3,4,5,6, 7,8,9,10,11,12,13,14,15,"16+"];
$data["bed_type"] = \App\Models\BedType::where("status", "Active")->pluck("name", "id");
$data["bathrooms"] = [1,2,3,4,5,6,7,"8+"];
$data["property_type"] = \App\Models\PropertyType::where("status", "Active")->pluck("name", "id");
$data["room_type"] = \App\Models\RoomType::where("status", "Active")->pluck("name", "id");
$data["lan_description"] = \App\Models\RoomsDescriptionLang::where("room_id", $request->id)->get();
$data["accommodates"] = [0,1,2,3,4,5,6, 7,8,9,10,11,12,13,14,15,"16+"];
$data["country"] = \App\Models\Country::pluck("long_name", "short_name");
$data["amenities"] = \App\Models\Amenities::active_all()->groupBy("type_id");
$data["users_list"] = \App\Models\User::pluck("first_name", "id");
$data["room_id"] = $request->id;
$data["result"] = \App\Models\Rooms::find($request->id);
// dd($data['result']);
$data["rooms_photos"] = \App\Models\RoomsPhotos::where("room_id", $request->id)->get();
$data["calendar"] = str_replace(["<form name=\"calendar-edit-form\">", "</form>", url("manage-listing/" . $request->id . "/calendar")], ["", "", "javascript:void(0);"], $calendar->generate($request->id));
$data["prev_amenities"] = explode(",", $data["result"]->amenities);
// dd($data["prev_amenities"]);
$data["length_of_stay_options"] = \App\Models\Rooms::getLenghtOfStayOptions();
$data["availability_rules_months_options"] = \App\Models\Rooms::getAvailabilityRulesMonthsOptions();
// dd($data);
return view("admin.rooms.edit", $data);
}
$accommodates[$i] = $i == 16 ? $i . "+" : $i;
$i++;
}
$bathrooms[(string) $i] = $i == 8 ? $i . "+" : $i;
$i += 0;
}
$beds[$i] = $i == 16 ? $i . "+" : $i;
$i++;
}
$bedrooms[$i] = $i;
$i++;
}
And view file as follows:
{!! Form::open(['url' => ADMIN_URL.'/edit_room/'.$room_id='', 'class' => 'form-horizontal', 'id' => 'add_room_form', 'files' => true]) !!}
<input type="hidden" value="{{ $room_id }}" name="room_id" id="room_id">
<div id="sf1" class="frm">
<fieldset class="box-body">
<div id="ajax_container" class="iccon">
{!! $calendar??'' !!}
</div>
</fieldset>
</div>
<div id="sf2" class="frm">
<p class="text-danger">
(*)Fields are Mandatory
</p>
<fieldset class="box-body">
<p class="text-success text-bold">
Rooms and Beds
</p>
<div class="form-group">
<label for="bedrooms" class="col-sm-3 control-label">
Bedrooms
<em class="text-danger">
*
</em>
</label>
<div class="col-sm-6">
{!! Form::select('bedrooms', $bedrooms='', $result->bedrooms, ['class' => 'form-control', 'id' => 'bedrooms', 'placeholder' => 'Select...']) !!}
</div>
</div>
<div class="form-group">
<label for="beds" class="col-sm-3 control-label">
Beds
<em class="text-danger">
*
</em>
</label>
<div class="col-sm-6">
{!! Form::select('beds', $beds, $result->beds, ['class' => 'form-control', 'id' => 'beds', 'placeholder' => 'Select...']) !!}
</div>
</div>
<div class="form-group">
<label for="bed_type" class="col-sm-3 control-label">
Bed Type
<em class="text-danger">
*
</em>
</label>
<div class="col-sm-6">
{!! Form::select('bed_type', $bed_type, $result->bed_type, ['class' => 'form-control', 'id' => 'bed_type', 'placeholder' => 'Select...']) !!}
</div>
</div>
I am not getting what is wrong in that. in dd($result) getting all attributes values but not getting ehy this errors comes
Current i am working on laravel5.5 version.
ANyone have idea thwn please let me know

Laravel Image Upload not saving to public folder

I am struggling with this image upload system.
It is supposed to upload an image that will be attached to a post (each post has 1 image).
Everything seems to be working fine, the problem is that when I check the database for the image path, I see a path to a random temporary file and the image doesn't even get uploaded to the right folder inside the app public folder.
Check the logic below:
PostController.php
public function store(Request $request)
{
$post = new Post;
$request->validate([
'title' => 'required',
'description' => 'required',
'slug' => 'required',
'message' => 'required',
'user' => 'required',
'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if ($request->has('post_image')) {
$image = $request->file('post_image');
$name = Str::slug($request->input('title')).'_'.time();
$folder = '/uploads/images/';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$post->post_image = Storage::url($filePath);;
}
Post::create($request->all());
return \Redirect::to('admin')->with('success','Great! Post created successfully.');
}
UploadTrait.php
trait UploadTrait
{
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : Str::random(25);
$file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);
return $file;
}
}
Post.php (model)
class Post extends Model
{
protected $fillable = [
'title',
'description',
'slug',
'message',
'user',
'post_image'
];
public function getImageAttribute(){
return $this->post_image;
}
}
Create.blade.php
<form action="{{ route('blog.store') }}" method="POST" name="add_post" role="form" enctype="multipart/form-data">
{{ csrf_field() }}
<h1>New Post</h1>
<div role="separator" class="dropdown-divider"></div>
<div class="form-row">
<div class="form-group col-12 col-md-6">
<label for="title">Post Title</label>
<input type="text" autocomplete="off" class="form-control" id="title" name="title" placeholder="Your post title" required>
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group col-12 col-md-6">
<label for="slug">Slug</label>
<input type="text" autocomplete="off" class="form-control" id="slug" name="slug" placeholder="Write post slug" required>
<span class="text-danger">{{ $errors->first('slug') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-12 col-md-12">
<label for="description">Post Description</label>
<textarea class="form-control" id="description" name="description" placeholder="Enter a small description for your post" required></textarea>
<span class="text-danger">{{ $errors->first('description') }}</span>
</div>
</div>
<div class="badge badge-warning badge-pill">Message</div>
<div role="separator" class="dropdown-divider"></div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" col="4" id="message" name="message"></textarea>
<span class="text-danger">{{ $errors->first('message') }}</span>
</div>
</div>
<input type="hidden" value="{{ Auth::user()->name }}" name="user">
<input id="post_image" type="file" class="form-control" name="post_image">
<button type="submit" class="btn btn-warning btn-block">Create Post</button>
</form>
Thank you for your help!
Regards,
Tiago
You can use directly the functions provided by Laravel itself
$image_path = Storage::disk('public')->putFile('folders/inside/public', $request->file('post_image'));
Notice Storage::disk('public') that specifies the public folder.
Then you can update your request array with $request['image_path'] = $image_path and save it like you're currently doing or you cant still use your $post = new Post; and set every input data like $post->title = $request->title; then save like $post->save();
You did not save the image path in the database on the created post
$post = new Post; //here you have created an empty Post object
...
$post->post_image = Storage::url($filePath); //here you assigned the post_image to the empty object.
Post::create($request->all());// here you create a new POST object with the request data, which does not contain the post_image
Thank you David! I managed to correct the path that gets saved to the database, but the files are not getting uploaded (even though the path in database says /uploads/images/something.png, when i check the folder, the image is not there.. there is not even an uploads folder. This is the method I have now with your suggestions:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'slug' => 'required',
'message' => 'required',
'user' => 'required',
'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if ($request->has('post_image')) {
$image = $request->file('post_image');
$name = Str::slug($request->input('title')).'_'.time();
$folder = '/uploads/images';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$image_path = Storage::disk('public')->putFile('uploads/images', $request->file('post_image'));
$request['image_path'] = $image_path;
}
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->slug = $request->slug;
$post->message = $request->message;
$post->user = $request->user;
$post->post_image = $request->image_path;
$post->save();
return \Redirect::to('admin')->with('success','Great! Post created successfully.');
}
Input in form
<form method="POST" enctype="multipart/form-data" action="/url">
<input id="category_logo" type="file" class="form-control" name="category_logo">...
Code in controller
$category = Category::find($id);
if($request->has('category_logo')) {
$image = $request->file('category_logo');
$category->category_logo = $image->getClientOriginalName();
$image->move(public_path('img/logo'), $image->getClientOriginalName());
}
$category->save();
Works for me!

Laravel filter reset after next page click in paginate

I have created a table were showing data. I also add few filters to filter data. Using paginate I show 20 records per page. After select filter and click search records in table filter with paginating on the first page but as soon as I click next page filters getting reset. How to stop filters from getting reset?
Below is my code,
public function index()
{
$agos = DB::table('orders')
->leftJoin('companies', 'orders.company_id', '=', 'companies.id')
->select(DB::raw('orders.id, companies.name, orders.type, orders.data, orders.currency, orders.price, orders.status, DATE_FORMAT(orders.created_at,"%M %d, %Y") as created_at '))
->where('orders.merchant', '=', 'agos')
->where(function ($query) {
$status = Input::has('status') ? Input::get('status') : null;
$company = Input::has('company') ? Input::get('company') : null;
$from = Input::has('from_date') ? Input::get('from_date') : null;
$to = Input::has('to_date') ? Input::get('to_date') : null;
$from = date("Y-m-d", strtotime($from));
$to = date("Y-m-d", strtotime($to));
if ( isset($status) ) {
$query->where('orders.status', '=', $status);
}
if ( isset($company) ) {
$query->where('companies.name', '=', $company);
}
if ( !empty($from) && !empty($to) ) {
$query->whereBetween('orders.created_at', [$from, $to]);
}
})->orderBy('orders.created_at', 'desc')
->paginate(20);
return $agos;
}
Blade file code,
#extends('layouts.agos')
#section('title', Translator::transSmart('app.Common Clerk(AGOS)', 'Common Clerk(AGOS)'))
#section('styles')
#parent
{{ Html::skinForVendor('jquery-textext/all.css') }}
#endsection
#section('scripts')
#parent
{{ Html::skinForVendor('jquery-textext/all.js') }}
#endsection
#section('content')
<div class="admin-managing-member-index">
<div class="row">
<div class="col-sm-12">
{{ Form::open(array('route' => array('agos::index'), 'class' => 'form-search')) }}
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'company';
$translate = Translator::transSmart('app.Company', 'Company');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{ Form::select($name, $companies->pluck('name', 'name'), Request::get($name), array('id' => $name, 'title' => $translate, 'class' => 'form-control', 'title' => $name, 'placeholder' => '')) }}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'status';
$translate = Translator::transSmart('app.Status', 'Status');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{Form::select($name, Utility::constant('agos_status', true), Request::get($name), array('id' => $name, 'class' => 'form-control', 'title' => $translate, 'placeholder' => ''))}}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'from_date';
$translate = Translator::transSmart('app.From', 'From');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'to_date';
$translate = Translator::transSmart('app.To', 'To');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 toolbar">
<div class="btn-toolbar pull-right">
<div class="btn-group">
{{
Html::linkRouteWithIcon(
null,
Translator::transSmart('app.Search', 'Search'),
'fa-search',
array(),
[
'title' => Translator::transSmart('app.Search', 'Search'),
'class' => 'btn btn-theme search-btn',
'onclick' => "$(this).closest('form').submit();"
]
)
}}
</div>
</div>
</div>
</div>
{{ Form::close() }}
</div>
</div>
<div class="row" >
<div class="col-sm-12">
<hr />
</div>
</div><br>
<div class="row" style="background-color:#FFFFFF">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-condensed table-crowded">
<thead>
<tr>
<th>{{Translator::transSmart('app.#', '#')}}</th>
<th></th>
<th>{{Translator::transSmart('app.Company', 'Company')}}</th>
<th>{{Translator::transSmart('app.Products', 'Products')}}</th>
<th>{{Translator::transSmart('app.Total Price', 'Total Price')}}</th>
<th>{{Translator::transSmart('app.Status', 'Status')}}</th>
<th>{{Translator::transSmart('app.Created At', 'Created At')}}</th>
<th></th>
</tr>
</thead>
<tbody>
#if($orders->isEmpty())
<tr>
<td class="text-center empty" colspan="14">
--- {{ Translator::transSmart('app.No Record.', 'No Record.') }} ---
</td>
</tr>
#endif
<?php $count = 0;?>
#foreach($orders as $order)
<tr>
<td>{{++$count}}</td>
<td></td>
<td>{{$order->name}}</td>
<td>
#php
$json = $order->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['name']. ', ';
}
$data = rtrim($data, ', ');
#endphp
{{$data}}
</td>
<td>
#if(empty($order->price) || $order->price == 0)
{{'Quotation'}}
#else
{{CLDR::showPrice($order->price, $order->currency, Config::get('money.precision'))}}
#endif
</td>
<td>{{Utility::constant(sprintf('agos_status.%s.name', $order->status))}}</td>
<td>{{$order->created_at}}</td>
<td class="item-toolbox">
{{
Html::linkRouteWithIcon(
'agos::edit',
Translator::transSmart('app.Edit', 'Edit'),
'fa-pencil',
['id' => $order->id],
[
'title' => Translator::transSmart('app.Edit', 'Edit'),
'class' => 'btn btn-theme'
]
)
}}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="pagination-container">
#php
$query_search_param = Utility::parseQueryParams();
#endphp
{!! $orders->render() !!}
</div>
</div>
</div>
</div>
#endsection
Controller Code,
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Can someone help me?
Try to append the request in the results:
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
$queryArgs = Input::only(['status','company','from_date', 'to_date']);
$orders->appends($queryArgs);
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Then in your template:
<div class="pagination-container">
{!! $orders->render(); !!}
</div>
try to use in your Blade view
$orders->links()

Summernote WYSIWYG editor not rendering data correctly with Laravel 5.8

I have a problem when I want to rendering data and Images from database, I'm using Summernote and Laravel, I will paste my Code of the controller and views, thanks in advance.
I get summer note show correctly with all his options, but when I try to add some things in my text like make it bold or something like that he did not work.
Controller:
public function createPost(Request $request){
$this->validate($request, [
'title' => 'required',
'description' => 'required',
]);
$title = $request->input('title');
$description = $request->input('description');
$writer = Auth::user()->id;
$dom = new \DomDocument();
$dom->loadHtml($description, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
$data = $img->getAttribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name= "/upload/" . time().$k.'.png';
$path = public_path() . $image_name;
file_put_contents($path, $data);
$img->removeAttribute('src');
$img->setAttribute('src', $image_name);
}
$description = $dom->saveHTML();
$post = new Post;
$post->title= $title;
$post->description = $description;
$post->writer = $writer;
$post->save();
return redirect()->route('home')->with('success', 'Post has been successfully added!');
}
Add view:
#if(Auth::check())
<div class="col-md-12">
<form method="post" action="{{ route('post.form') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Title</label>
<input type="text" class="form-control" id="id_title" name="title"
aria-describedby="title" placeholder="Enter title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="content" rows="3" name="description" placeholder="Description"></textarea>
</div>
<button type="submit" class="btn btn-primary">Publish <i class="fas fa-paper-plane"></i></button>
</form>
</div>
#endif
Call of the summernote:
<script>
$(document).ready(function() {
$('#content').summernote({
height:300,
});
});
</script>
Example of the result, title plus content :
You should use {!! $description !!} to print as html.
Inspect the output in the browser, maybe the summernote plugin is not called properly,
In head tag, check the javascript plugin, and the css as well. Put them is proper order.

Laravel 5.2 TokenMismatchException

I'd like to write a code in Laravel 5.2 which would upload photos, my problem is that once I start uploading many photos at once the site goes down.
It gives me this error: TokenMismatchException in VerifyCsrfToken.php line 67:
This error should appear only when the {{ csrf_field() }}, is missing from the form, but in this case it isn't, it's right there.
It works perfectly with less images. What could be the problem?
Controller
public function store(Request $request)
{
$rules = array(
'picturess' => 'mimes:jpeg,jpg,bmp,png',
);
$messages = array(
'mimes' => 'A feltöltetni kívánt kép nem felel meg a kritériumoknak. (Ilyen lehet a kép kiterjesztése: jpeg, jpg, bmp vagy png. A kép se lehet bármekkora.)',
'integer' => 'A beírt szőveg nem szám.',
'required' => 'Ennek a mezőnek a kitőltése kötelező.',
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withInput()->withErrors($validator);
}
if (Input::hasFile('pictures')) {
$files = $request::file('pictures');
$file_count = count($files);
$uploadcount = 0;
$destinationPath = 'uploads';
$userId = Auth::user()->id;
foreach ($files as $file) {
if ($file->isValid()) {
$extension = $file->getClientOriginalExtension();
$pictureFileName = $this->makePictureFileName(0, $extension);
$thumbnailPictureFileName = $this->makePictureFileName(1, $extension);
Log::info('pictureFileName: '.$pictureFileName);
if ($file->move($destinationPath, $pictureFileName)) {
$uploadcount++;
$img = Image::make($destinationPath . '/' . $pictureFileName);
//$img = Image::make($file->getClientOriginalName());
$img->resize(277, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save($destinationPath . '/' . $thumbnailPictureFileName);
$picture = new Picture;
$picture->filename = $pictureFileName;
$picture->thumbnail_filename = $thumbnailPictureFileName;
$picture->user_id = $userId;
$picture->save();
}
} else {
Session::flash('picture-error', 'A feltöltetni kívánt kép nem megfelelő. (Valószínűleg túl nagy.)');
return redirect()->back()->withInput()->withErrors($validator);
}
}
if ($uploadcount == $file_count) {
Session::flash('success', 'A képek feltöltése sikeres.');
} else {
return redirect()->back()->withInput()->withErrors($validator);
}
}
//return Redirect::to('pictures/create');
return redirect()->back()->withInput()->withErrors($validator);
}
View
#extends('layouts.site')
#section('content')
<div class="row">
<div class="col-md-12">
{!! Form::open(array('method' =>'POST', 'url' => 'pictures', 'class' => 'uk-form', 'files'=> true)) !!}
{{ csrf_field() }}
<div class="form-group">
{!! Form::label('pictures', 'Kép', array('class' => '')) !!}
<div class="uk-form-controls">
{!! Form::file('pictures[]', array('class' => '','multiple'=>true)) !!}
</div>
</div>
<div class="form-group">
<button class="uk-button">Küldés</button>
</div>
#if ($errors->has('success'))
<div class="alert alert-danger" role="alert">
<p>{{ $errors->first('success') }}</p>
</div>
#endif
#if(Session::has('picture-error'))
<div class="alert alert-danger" role="alert">
<p class="errors">{!! Session::get('error') !!}</p>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::close() !!}
</div>
</div>
#stop
Route
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'SiteController#index');
Route::get('admin', 'AdminController#index');
Route::resource('pictures', 'PicturesController');
Route::resource('users', 'UsersController');
Route::auth();
});
{!! Form::open... will automatically add CSRF field protection, so you don't need this {{ csrf_field() }}.

Resources