I have create a two different feed component with Laravel and vue js, the first one is pure using laravel controller and passing the data to view. Another one is using controller and passing to vue.js file.
But i trying to combine two together since is would be more user friendly for me which is fetching data into view and binding with vue button.
i had tried with this code but having error.Is there possible to do that?
#foreach($feeds as $feed)
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow">
<div class="post-heading">
<div class="pull-left image">
<img src="{{$feed->user->avatar}}" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ $feed->user->name }}
made a post.
</div>
<h6 class="text-muted time">{{ $feed->created_at->diffForHumans() }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ $feed->content }}</p>
<div class="stats">
<like id="{{$feed->id}}"></like> <objection id="{{$feed->id}}"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
But the problems is how to passing the id into my vue which is
<like :id="post.id"></like>
<objection :id="post.id"></objection>
Here is my Feed.vue file
<template>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow" v-for="post in posts">
<div class="post-heading">
<div class="pull-left image">
<img :src="post.user.avatar" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ post.user.name }}
made a post.
</div>
<h6 class="text-muted time">{{ post.created_at }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ post.content }}</p>
<div class="stats">
<like :id="post.id"></like>
<objection :id="post.id"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
<comment :id="post.id"></comment>
</div>
</div>
</div>
</div>
<script>
import Like from './Like.vue'
import Comment from './Comment.vue'
import Objection from './Objection.vue'
export default{
mounted(){
this.get_feed()
},
components:{
Like,
Objection,
Comment
},
methods:{
get_feed(){
this.$http.get('/feed')
.then( (response)=>{
response.body.forEach( (post) =>{
this.$store.commit('add_post',post)
})
})
},
},
computed: {
posts(){
return this.$store.getters.all_posts
}
}
}
This is one of my Like components.
<template>
<button class="btn btn-basic" v-if="!auth_user_likes_post" #click="like()">
True {{ likers.length }}
</button>
<button class="btn btn-primary" v-else #click="unlike()">
Untrue {{ likers.length }}
</button>
<script>
export default {
mounted(){
},
props: ['id'],
computed: {
likers() {
var likers = []
this.post.likes.forEach( (like) => {
likers.push(like.user.id)
})
return likers
},
auth_user_likes_post() {
var check_index = this.likers.indexOf(
this.$store.state.auth_user.id
)
if (check_index === -1)
return false
else
return true
},
post() {
return this.$store.state.posts.find( (post) => {
return post.id === this.id
})
}
},
methods: {
like() {
this.$http.get('/like/' + this.id)
.then( (resp) => {
this.$store.commit('update_post_likes', {
id: this.id,
like: resp.body
})
})
},
unlike() {
this.$http.get('/unlike/' + this.id)
.then( (response) => {
this.$store.commit('unlike_post', {
post_id: this.id,
like_id: response.body
})
})
}
}
}
Can you take a look at this https://scotch.io/tutorials/implement-a-favoriting-feature-using-laravel-and-vue-js, might be helpful.
It explains in details how you setup the Model in a proper way, the computed, and methods, also the steps are just too easy to follow.
I noticed that you have:
mounted(){
//blank
}
You could add some functionality like:
mounted() {
this.isFavorited = this.isFavorite ? true : false;
}
This will help handle the toggle part
Related
I'm trying to implement a live search in my laravel application.
Following is my index function in the controller (ParticipantController.php). Here if there is no search happens, then displaying the participants by default.
public function index(Request $request)
{
if($request->ajax()){
$data = User::orderBy('id','DESC')
->WHERE('role_id','=','3')
->where('email','LIKE','%'.$request->search."%")
->paginate(12);
return view('admins.participants.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
}
else{
$data = User::orderBy('id','DESC')->WHERE('role_id','=','3')->paginate(12);
return view('admins.participants.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
}
}
following is my view (only included the relevant part)
<div class="row mt-5 ">
<div class="col-md-12 mb-2 text-right">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
</div>
<div class="row mt-2 participant-row">
#foreach ($data as $key => $user)
<div class="col-md-3 d-flex align-items-stretch mb-4">
<div class="white-panel w-100 ">
<div class="card p-2 ">
<div class="row no-gutters ">
<div class="col-auto my-auto">
#if(empty($user->image_id))
<img src="/propics/default-avatar.png" class="img_participant">
#else
<?php if(file_exists('propics/'.$user->image_id.'')){
echo '<img src="/propics/'.$user->image_id.'" class="img_participant">
';
}else{
echo '<img src="/propics/default-avatar.png" class="img_participant">
';
}?>
#endif
</div>
<div class="col my-auto">
<div class="card-block px-2">
<div class="text-right">
<a class="btn btn-default btn_icon" href="{{ route('participants.edit',$user->id) }}"><i class="fas fa-edit"></i></a>
{!! Form::open(['method' => 'DELETE','route' => ['participants.destroy', $user->id],'style'=>'display:inline']) !!}
{!! Form::button('<i class="fas fa-trash-alt"></i>', ['class' => 'btn btn-default btn_icon','type'=>'submit','onclick'=>'return confirm("Are you sure want to remove this User?")']) !!}
{!! Form::close() !!}
</div>
<hr>
<h4 class="card-title participant_name alas">{{ $user->first_name }} {{ $user->last_name }}</h4>
<p class="card-text participant_email alas">{{ $user->email }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
And set my route as (web.php),
Route::resource('/admins/participants','Admin\ParticipantController');
Following is my Javascript which I included at the bottom of my view
<script type="text/javascript">
jQuery('#search').on('keyup',function(){
$value=jQuery(this).val();
$.ajax({
type : 'get',
url:"{{ route('participants.index') }}",
data:{'search':$value},
success:function(data){
jQuery('.participant-row').html(data);
}
});
})
</script>
Now the issue is when I search for something, as the result, the current code provides me a whole new view inside the old view. It loads a new view (with the menus and all) inside the target div class whichi mentioned in my javascript code.
I'm making an e-commerce capstone project. The query is already okay but the problem is with displaying the data. If I choose a different category the current category will be hidden and only the new category will be displayed.
https://imgur.com/a/YsLj9S2
<section>
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-9" style="border:solid 1px;">
<div class="row">
<div class="col-sm-4" id="test3">
<div class="card" id="test">
<div class="card-body" id="test2">
<div class="product-grid">
<div class="product-image">
<a href="#" class="image" style="background-color:#F3F3F3;">
<img class="pic-1" src="https://media.comicbook.com/2020/05/dragon-ball-super-when-will-should-goku-master-ultra-instinct-1219439.jpeg?auto=webp&width=1200&height=628&crop=1200:628,smart" class="d-block w-100" id>
</a>
<a class="add-to-cart" id="cart" href=""> + </a>
</div>
<div class="product-content">
<h3 class="title" id="productname">Product Name</h3>
<div class="price" id="price"></div>
</div>
<div class="action-buttons">
<button class="btn btn-danger mt-3" id="cart" onclick="addtocart()"><i class="fas fa-shopping-cart"></i> Add to Cart</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
function searchcategory(category_id) {
$.ajax({
url: "<?php echo base_url() ?>admin/getproducts/" + category_id,
type: "POST",
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
let row = `<div class="price" id="price">${value.price}</div>`;
let val = `<h3 class="title" id="productname">${value.product_name}</h3> `;
let test = `<button class="btn btn-danger mt-3" id="cart" onclick="${value.product_id}" ><i class="fas fa-shopping-cart"></i> Add to Cart</button>`;
$('#price').append(row);
$('#price').append();
$('#productname').append(val);
/* $('#test3').append(val);
$('#cart').text(test); */
console.log(test);
});
}
});
}
Im new to Laravel framework and im trying to develop a simple car listing web using Bootstrap Cards. I've successfully implemented AJAX Get including populating data from Controller using Jquery append() method. However it is displaying all cars in one Card. How to populate each Cards containing each car?. current result console.log result
public function GetCars(Request $request)
{
if ($request->ajax())
{
$cars = Car::all();
return response()->json( $cars );
}
}
<div class="album py-1">
<div class="container bg-light">
<div class="row py-2">
<div class="col-md-3">
<div class="card mb-3 shadow-sm">
<div class="hover-container">
<img src="" class="image img-thumbnail">
<a class="Viewbtn text-decoration-none" href="#" style="font-size: small">View</a>
</div>
<div class="card-body CarDetail">
<p class="card-text font-weight-bold">Make:<span class="car_Make"></span></p>
<p class="card-text font-weight-bold">Model:<span class="car_Model"></span></p>
<div class="d-flex justify-content-between align-items-center">
<p class="font-italic table_data">Price: RM <span class="car_Year"></span></p>
</div>
</div>
</div>
</div>
</div>
</div>
<button id="testbtn" type="submit" class="btn btn-success">AJAX</button>
</div>
<script>
$(document).ready(function(){
$('#testbtn').click(function () {
$.ajax({
type: 'GET',
url: '/ajax/getCar',
success : function (data) {
$.each(data, function( i, car ) {
$('.car_Make').append(car.make);
$('.car_Model').append(car.model+'<br>');
$('.car_Year').append(car.year+'<br>');
});
}
});
});
});
</script>
This is what are you meaning?
I created an example, where I'm using some rows from your console.log data.
Explanation:
I am iterating throught the data array. If it is first iteration I'm adding data (one CarDetail div exists in your code.
For the next iterations I am cloning the CarDetail div and fill with next data.
Of course,there are more posibilities how to add your data to page. For example, you can fill the first item in page and then iterate from the second to the last (in that case you won't need the if/else condition) or you can add the HTML code in a JS variable. Personally, I wouldn't do that because it looks very ugly and the readability of the code could get worse.
$(document).ready(function(){
var data = [
{id:31,make:"Audi",model:"R8",year:2000},
{id:32,make:"Ferrari",model:"FF",year:2000},
{id:33,make:"Mazda",model:"Rx-7",year:2000},
{id:34,make:"Ferrari",model:"F12",year:2012},
{id:35,make:"Porsche",model:"911",year:2015},
{id:36,make:"Land Rover",model:"Vogue",year:2015},
{id:37,make:"Mercedes Benz",model:"SL350",year:2013},
{id:38,make:"Ferrari",model:"F12",year:2013},
{id:39,make:"Ferrari",model:"458",year:2013},
];
$.each(data, function( i, car ) {
if(i == 0) {
$('.card').find('.car_Make').text(car.make);
$('.card').find('.car_Model').text(car.model);
$('.card').find('.car_Year').text(car.year);
} else {
var carDetailCloned = $('.card').first().clone();
carDetailCloned.find('.car_Make').text(car.make);
carDetailCloned.find('.car_Model').text(car.model);
carDetailCloned.find('.car_Year').text(car.year);
$('.card-container').append(carDetailCloned);
}
});
});
.CarDetail{background-color:red;margin-bottom:2em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="album py-1">
<div class="container bg-light">
<div class="row py-2">
<div class="col-md-3 card-container">
<div class="card mb-3 shadow-sm">
<div class="hover-container">
<img src="" class="image img-thumbnail">
<a class="Viewbtn text-decoration-none" href="#" style="font-size: small">View
</a>
</div>
<div class="card-body CarDetail">
<p class="card-text font-weight-bold">Make:
<span class="car_Make"></span>
</p>
<p class="card-text font-weight-bold">Model:
<span class="car_Model"></span>
</p>
<div class="d-flex justify-content-between align-items-center">
<p class="font-italic table_data">Price: RM
<span class="car_Year"></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<button id="testbtn" type="submit" class="btn btn-success">AJAX</button>
</div>
Edit: I edited my code to clone <div class="card mb-3 shadow-sm" for every card and add data in there. Moreover, I add a card-container class in the parent element to use it when I append a new car. Is that enough?
My route as below;
Route::post ('/sepetim', 'ShoppingCartController#addStock');
My controller as below;
public function addStock(Request $request) {
$data = new ShoppingCartDetail();
$data->cart_id = $request->input('cart_id');
$data->stock_id = $request->input('stock_id');
$data->price = 1;
$data->save();
}
My ajax as below:
$.ajax({
type: 'POST',
url: '/sepetim',
data: {
'_token': $('input[name="_token"]').val(),
'name': $('input[name=name]').val(),
'cart_id': $('input[name=cart_id]').val(),
'stock_id': id
},
success: function(data) {
// alert("Başarılı bir şekilde eklendi.");
},
});
The div I want to update with Ajax.
#foreach($all_values_list as $row)
<div class="sepeturunalan row d-flex align-items-center">
<div class="col-lg-1 col-sm-1 col-1">
<img src="http://vomsis.com/uploads/thumb_{{$row['imageable_name']}}" class="img-fluid">
</div>
<div class="col-lg-4 col-sm-4 col-12 pl">
<a href="#" title="">
{{$row['stock_name']}}
</a>
</div>
<div class="col-lg-2 col-sm-2 col-2 text-center">
<span class="para">{{number_format($row['without_tax'] , '2' , ',' , '.')}}</span>
</div>
<div class="col-lg-1 col-sm-1 col-1 plr text-center">
<span class="para">{{number_format($row['new_price'] - $row['without_tax'] , '2' , ',' , '.')}} TL</span> <br/>
<span class="fw">(%{{$row['tax_ratio']}})</span>
</div>
<div class="col-lg-2 col-sm-2 col-2 text-center">
<div class="input-group adet">
<span class="input-group-btn">
<button type="button" id="{{$row['id'].'u'}}" class="btn-number" onclick="buttons_click_minus({{$row['id']}})" data-type="minus" data-field="quant[1]">
<i class="fa fa-minus"></i>
</button>
</span>
{{ csrf_field() }}
{{ Form::hidden('cart_id', $cart_id) }}
{{ Form::hidden('stock_id', $row['id']) }}
<input type="text" id="{{$row['id']}}" name="name" class="input-number" onchange="input_onchange(this.id)" value="{{$row['quantity']}}" min="1" max="25">
<span class="input-group-btn">
<button type="button" type="submit" id="{{$row['id']}}" class="btn-number" onclick="buttons_click_plus(this.id)" data-type="plus" data-field="quant[1]">
<i class="fa fa-plus"></i>
</button>
</span>
</div>
</div>
<div class="col-lg-2 col-sm-2 col-2 text-right">
<span class="para fw6">{{number_format($row['quantity'] * $row['new_price'] , '2' , ',' , '.')}} TL</span> <br/>
<span>
{!! Form::open(['url' => '/sepetim/'.$cart_id .'/'.$row['id'], 'method' => 'delete']) !!}
<button type="submit" class="sepsil">
<i class="fa fa-trash-o"></i> Sil
</button>
{!! Form::close() !!}
</span>
</div>
<div class="col-lg-6 col-sm-6 col-6">
<p class="aciklama">
<i class="fa fa-info-circle renk"></i>
<span class="para">100TL </span> üzeri kargo bedava! kampanyasına dahil ürün
</p>
</div>
</div>
#endforeach
The above code is registering to the database. My question: How can I show data stored in a database with ajax - Laravel?
enter image description here
Ajax is working when button is clicked. Registering to the database. How can I show.
After $data->save();, do something like return response()->json(["data" => $data]);, which passes $data to your success: function(data) as a json object available via data.data:
Controller Function (PHP):
public function addStock(Request $request) {
...
return response()->json(["data" => $data]);
}
Success Function (JS):
...
success: function(data) {
console.log(data.data); // (May want to change your PHP return value to something other than data)
},
To actually display the returned data in your page, you would either need to return some HTML via the addStock method, or construct some HTML in your success function:
Controller Function (PHP)
public function addStock(Request $request){
...
$renderedHtml = view("example")->with(["data" => $data])->render();
return response()->json(["data" => $data, "renderedHtml" => $renderedHtml]);
}
Success Function (JS):
...
success: function(data) {
$("#someDiv").html(data.renderedHtml);
// OR
var renderedHtml = "<div>";
renderedHtml += "<span>$" + data.data.price + "</span>";
// etc etc
renderedHtml += "</div>";
$("#someDiv").html(renderedHtml);
},
I have really no idea where the problem resides to be honest.
Might be Dropzone, Laravel (5.4), ... So I truly hope even a thought might help me get past this problem.
When I upload files, I don't get any js issues but Laravel throws me following error (for each file):
Call to undefined method Symfony\Component\HttpFoundation\File\UploadedFile::store()
This is my backend code (Error is set in the portfolioStore method):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UploadPortfolioPhotoRequest; use App\PortfolioPhoto; use DebugBar\DebugBar; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage;
class AdminController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.home');
}
public function portfolioIndex()
{
$photos = PortfolioPhoto::all();
return view ('admin.portfolio.index')->with('photos', $photos);
}
public function portfolioStore(UploadPortfolioPhotoRequest $request)
{
foreach ($request->files as $photo) {
$filename = $photo->store('photos');
$test = PortfolioPhoto::create([
'filename' => $filename,
'title' => 'title',
'alt' => 'alt'
]);
}
return 'Upload successful!';
}
public function portfolioDelete()
{
return view ('admin.portfolio.index');
} }
In any case, here is my Dropzone config:
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
url: "/admin/portfolio", // Set the url
thumbnailWidth: 80,
thumbnailHeight: 80,
parallelUploads: 20,
previewTemplate: previewTemplate,
autoDiscover: false,
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: "#previews", // Define the container to display the previews
clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
}
});
myDropzone.on("addedfile", function(file) {
// Hookup the start button
file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
});
myDropzone.on("sending", function(file) {
// And disable the start button
file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone.on("queuecomplete", function(progress) {
var alertMsg = document.createElement('div'),
actions = document.getElementById('actions');
alertMsg.setAttribute('class', 'alert bg-success');
alertMsg.innerHTML = 'Files successfully uploaded<em class="fa fa-lg fa-close"></em>';
actions.parentNode.insertBefore(alertMsg, actions.nextSibling);
});
// Setup the buttons for all transfers
// The "add files" button doesn't need to be setup because the config
// `clickable` has already been specified.
document.querySelector("#actions .start").onclick = function() {
myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
};
document.querySelector("#actions .cancel").onclick = function() {
myDropzone.removeAllFiles(true);
};
Here is the view:
#extends('admin.layouts.app')
#section('content')
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Upload images</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="row">
<div class="col-xs-12">
<div class="alert bg-danger" role="alert"><em class="fa fa-lg fa-warning"> </em>
<ul style="display: inline-block;">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<em class="fa fa-lg fa-close"></em>
</div>
</div>
</div>
#endif
<div id="actions" class="row">
<div class="col-xs-12">
<div class="form-group">
<button class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i><span>Add files...</span>
</button>
<button type="submit" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i> <span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel upload</span>
</button>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="files" id="previews">
<div id="template" class="file-row">
<div class="media">
<div class="media-left">
<img data-dz-thumbnail/>
</div>
<div class="media-body">
<h4 class="media-heading name" data-dz-name></h4>
<div class="col-xs-12"><strong class="error text-danger" data-dz-errormessage></strong></div>
<div class="col-xs-12">
<div class="col-sm-3">
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div class="col-sm-9 text-right">
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Portfolio</div>
<div class="panel-body">
<div class="row">
#foreach($photos as $photo)
<div class="col-xs-6 col-md-3">
<a href="#" class="thumbnail">
<img src="..." alt="...">
</a>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>#endsection
#push('styles')
<link href="{{asset('css/vendor/dropzone.css')}}"/>
#endpush
#push('scripts')
<script src="{{asset('js/vendor/dropzone.js')}}"></script>
<script src="{{asset('js/vendor/initialize/dropzone.cfg.js')}}"></script>
#endpush
So now I'm wondering whether the issue is related to a MIME type being undefined which cause the store method to not work. Or should I be looking elsewhere?
Any advice, ideas welcome :)
The problem here is that the $request->files does not exist in the Laravel codebase. Since the Illuminate\Http\Request class extends the Symfony\Component\HttpFoundation\Request class, the files refers to the Symfony\Component\HttpFoundation\FileBag class which does happens to contain numerous Symfony\Component\HttpFoundation\File\UploadedFiles that do not have the store method.
Simple fix:
Replace $request->files with $request->allFiles() which should give you an array of Illuminate\Http\UploadedFile classes which have the store method
Feel free to shoot any questions in the comment section if you need further help
This seems to be no issue of dropzone.js to me.
The error says "undefined method..." in the backend (laravel), so the method is not available to your object photo.
Have a look at the docs in laravel. (https://laravel.com/docs/5.4/filesystem#file-uploads)
Maybe you can try something like this:
foreach ($request->files as $photo) {
$path = Storage::putFile('photos', $photo);
...
I had a similar problem but in my case it was simply not having enctype="multipart/form-data" property included in the <form> tag. Once I did that it worked. And I see you also don't have <form> tag.
<form action="/route" method="post" enctype="multipart/form-data">
<!-- your code for dropzone goes here -->
</form>
And on a side note, in your portfolioStore() method in your AdminController controller you have,
foreach ($request->allFiles() as $photo) {
$filename = $photo->store('photos');
$test = PortfolioPhoto::create([
'filename' => $filename,
'title' => 'title',
'alt' => 'alt'
]);
}
Please Don't do it!
You're creating too many insert queries here.
Refactor it as follows. You can get away with one db query :)
$photos = [];
foreach ($request->files as $photo) {
$filename = $photo->store('photos');
$photos[] = [
'filename' => $filename,
'title' => 'title',
'alt' => 'alt'
];
}
PortfolioPhoto::createMany($photos);
And also in a previous post I answered how to convieninetly store files in Laravel. you can check it out here. it could improve your $filename = $photo->store('photos'); part.
Hope this would help you :)
Just dump your $request object, dropzone may send base64_encoded images, that are not in $request->files array.
Anotherway, you can use
https://github.com/bnbwebexpertise/laravel-attachments
This is very helpful package to work with files.
UPDATED
In Laravel you access uploaded files using the file method, which takes the name of the file input as a parameter. And from the Dropzonejs docs:
The uploaded files can be handled just as if there would have been a html input like this:
<input type="file" name="file" />
So try this:
foreach ($request->file('file') as $photo) {