I've success to save the file image to my local folder in my laravel, but i get error when the image view is not found.
this is my createImage.blade.php
{!!Form::open(['route'=>'lowongan.store', 'method'=>'POST', 'files' => true])!!}
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('imgLoker')!!}
</div>
{!!Form::close()!!}
i was setting my config/filesystem for destination image where i saved.
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imageLoker'),
],
And this is my modal, i use Carbon
class Lowongan extends Model {
protected $table = 'Lowongan';
protected $fillable = ['judul','imgLoker','deskripsi', 'profilePt','deadline'];
public function setPathAttribute($path){
$name = Carbon::now()->second.$path->getClientOriginalName();
$this->attributes['imgLoker'] = $name;
\Storage::disk('local')->put($name, \File::get($path));
}
}
for my controller :
public function index() {
$lowongans = Lowongan::all();
return view('lowongan.index',compact('lowongans'));
}
public function store(Request $request)
{ Lowongan::create(
$request->all());
return "listtt";
}
i get error in this file, my image is not found. This is my index.blade.php
#foreach($lowongans as $lowongan)
<tr>
<td>
<img src="imageLoker/{{$lowongan->imgLoker}}" alt="" />
</td>
</tr>
#endforeach
Related
I have a problem with my project; the problem is the uploaded image to the database is not found and is not displaying on the page.
Galleries upload error
And these are the scripts.
gallery.blade.php
#foreach ($galleryImages as $galleryImage)
<div class="gallery-card">
<a href="detailed-gallery.html">
<img src="{{ asset('storage/' . $galleryImage->image_path) }}">
</a>
<p>{{ $galleryImage->title }}</p>
</div>
#endforeach
AppController.php
public function gallery()
{
$setting = \App\Setting::first();
$galleryImages = Gallery::all();
return view('gallery', compact('setting', 'galleryImages'));
}
GalleryController.php
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required',
'image_path' => 'required|image',
]);
Gallery::create(array_merge($data, ['image_path' => $data['image_path']->store('uploads/attachments', 'public')]));
return redirect()->route('galleries.index');
}
There are no errors on my friend's laptop, and they don't show on the page; what is it that the different OS affects? My friend is using Windows, and I'm using Ubuntu Linux; what's the solution?
I have a dynamic navigation bar, created however it won't show on the dynamic web page.
The current output is:
ErrorException
Undefined variable: navContent (View: C:\Users\Computer
Angel\Documents\blog\resources\views\page\dynamic.blade.php)
The desired output is my dynamic.blade.php where the pageContent is the dynamic page content the user inputted through a form and the dynamic navigation bar in the tags.
This is my dynamic.blade.php:
<nav>
#foreach($navContent as $nav)
{!!nav-navName!!}
#endforeach
</nav>
<body>
{!!$pageContent->pageContent!!}
</body>
This is my NavController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Nav;
use DB;
use Illuminate\Database\MySqlConnection;
class NavController extends Controller
{
public function index()
{
$navs = Nav::all();
return view('navManagement', compact('navs'));
}
public function create()
{
return view('createNav');
}
public function store(Request $request)
{
$data = request()->validate([
'navName' => 'required',
'navLink' => 'required',
]);
$nav = new Nav([
'navName' => $request->get('navName'),
'navLink' => $request->get('navLink'),
]);
$nav->save();
return redirect('/n');
}
public function show($navName)
{
$navContent = DB::table('navs')->where('navName',$navName)->first();
return view('page.dynamic', ['navContent' => $navContent]);
}
public function edit($navName)
{
$navContent = DB::table('navs')->where('navName',$navName)->first();
return view('editNav', ['navContent' => $navContent]);
}
public function update(Request $request)
{
$data = $request->validate([
'navName' => 'required|exists:navs,navName',
'navLink' => 'required'
]);
$obj = \App\Nav::where('navName', $request->navName)
->update([
'navLink' => $request->navLink
]);
return redirect('/n');
}
public function destroy(Request $request)
{
$obj = \App\Nav::where('navName', $request->navName)
->delete();
return redirect('/n');
}
}
This is my PageController.php:
<?php
namespace App\Http\Controllers;
use App\Page;
use Illuminate\Http\Request;
use DB;
use Illuminate\Database\MySqlConnection;
class PageController extends Controller
{
public function index()
{
$pages = Page::all();
return view('pageManagement', compact('pages'));
}
public function create()
{
//This will load create.blade.php
return view('createPage');
}
public function store(Request $request)
{
$data = request()->validate([
'title' => 'required',
'URI' => 'required|min:5|max:10|',
'pageContent' => 'required',
]);
$page = new Page([
'title' => $request->get('title'),
'URI' => $request->get('URI'),
'pageContent' => $request->get('pageContent'),
]);
$page->save();
return redirect('/p');
}
public function show($URI)
{
$pageContent = DB::table('pages')->where('URI',$URI)->first();
return view('page.dynamic', ['pageContent' => $pageContent]);
}
public function edit($URI)
{
$pageContent = DB::table('pages')->where('URI',$URI)->first();
return view('editPage', ['pageContent' => $pageContent]);
}
public function update(Request $request)
{
$data = $request->validate([
'title' => 'required',
'URI' => 'required|min:5|max:10|exists:pages,URI',
'pageContent' => 'required'
]);
$obj = \App\Page::where('URI', $request->URI)
->update([
'title' => $request->title,
'pageContent' => $request->pageContent
]);
return redirect('/p');
}
public function destroy(Request $request)
{
$obj = \App\Page::where('URI', $request->URI)
->delete();
return redirect('/p');
}
}
This is my Nav.php:
class Nav extends Model
{
protected $fillable = ['navName', 'navLink'];
}
This is my Page.php:
class Page extends Model
{
protected $fillable = ['title', 'URI', 'pageContent'];
}
This is my migration for pages:
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('URI');
$table->text('pageContent');
$table->timestamps();
});
}
This is my migration for nav:
public function up()
{
Schema::create('navs', function (Blueprint $table) {
$table->id();
$table->string('navName');
$table->string('navLink');
$table->timestamps();
});
}
This is my createNav.blade.php:
<form action="/storeNav" method="post">
#csrf
<label for="navName">Navigation Bar Option Name:</label><br>
<input type="text" id="navName" name="navName" autocomplete="off" value="{{ old('navName') }}">
<br>
#error('navName') <p style="color: red">{{ $message }}</p> #enderror
<label for="navLink">Navigation Bar Option Link:</label><br>
<input type="text" id="navLink" name="navLink" autocomplete="off" value="{{ old('navLink') }}">
<br>
#error('navLink') <p style="color: red">{{ $message }}</p> #enderror
<input type="submit" value="Submit">
</form>
This is my createPage.blade.php:
<form action="/storePage" method="post">
#csrf
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" autocomplete="off" value="{{ old('title') }}"><br>
#error('title') <p style="color: red">{{ $message }}</p> #enderror
<label for="URI">URI:</label><br>
<input type="text" id="URI" name="URI" autocomplete="off" value="{{ old('URI') }}"><br>
#error('URI') <p style="color: red">{{ $message }}</p> #enderror
<label for="pageContent">Page Content:</label><br>
<textarea id="pageContent" name="pageContent" value="{{ old('pageContent') }}"></textarea>
#error('pageContent') <p style="color: red">{{ $message }}</p> #enderror
<input type="submit" value="Submit">
</form>
This is my web.php:
Route::get('/page/{URI}', 'PageController#show');
Route::get('/page/{URI}/edit', 'PageController#edit');
Route::get('/p', 'PageController#index');
Route::get('/createPage', 'PageController#create');
Route::post('/storePage', 'PageController#store');
Route::patch('/page/{URI}', 'PageController#update');
Route::delete('/page/{URI}', 'PageController#destroy');
Route::get('/nav/{navName}/edit', 'NavController#edit');
Route::get('/n', 'NavController#index');
Route::get('/createNav', 'NavController#create');
Route::post('/storeNav', 'NavController#store');
Route::patch('/nav/{navName}', 'NavController#update');
Route::delete('/nav/{navName}', 'NavController#destroy');
Below is my github repository link, if you want to take a look at my full code, or you want to try run the code in your Integrated Development Environment.
https://github.com/xiaoheixi/blog
Thanks for reading! :D
If is complaining that it can't find a variable called $navContent.
I can't see you passing it to either of the views you are calling from your index() functions.
return view('navManagement', compact('navs'));
return view('pageManagement', compact('pages'));
You would need to set that varaible and pass it to the view
// Get the nav content however you want, this is just a crude example
$navContent = $this->getMyNavContent();
return view('navManagement', [
'navs' => $navs,
'navContent' => $navContent
]);
I'm guessing you want to find a way to embed the dynamic nav without having to add the navContent every time you render a view, as that's what the other answer is suggesting. You could achieve this using a middleware, say dynamicNav and registering your routes under that middleware group.
In that middleware you can do all the logic of fetching the nav content and then use something like merge, as shown here:
$request->merge(['dynamicNav' => $navContent]);
This way your middleware will add the data to every request which goes through it, although I wouldn't recommend this solution.
What I would do is cache the nav content and retrieve in the view using the cache() helper, then override the save() method of the model to also update the cache when the DB is updated (to avoid duplicate code, you could create a trait for the fetching of the nav). Example:
// in your model
public function save(array $options = [])
{
Cache::put('nav-content', getNavContent());
parent::save();
}
I have 2 Eloquent models:
/**
* Entities/Products.php
*/
use CrudTrait;
protected $fillable = [
'name', 'macronutrients_id',
];
public function macronutrients()
{
return $this->hasOne(Macronutrients::class);
}
/**
* Entities/Macronutrients.php
*/
use CrudTrait;
protected $fillable = [
'proteins', 'fats', 'carbons', 'calories', 'product_id'
];
public function product()
{
return $this->belongsTo(Product::class);
}
I don't know how I can show table (or something like list of options) with all macronutrients on product's edit page via Laravel Backpack CRUD?
In other words, I want to make something like this:
on page http://example.com/admin/product/2/edit:
* [text] Name
* Macronutrients:
[number] proteins
[number] fats
[number] carbons
[number] calories
where [text], [number] is input fields.
I resolved this with some custom logic. As a result:
Screenshot of my /admin/product/1/edit
First of all, I created custom field:
<!-- /resources/views/vendor/backpack/crud/fields/product_macronutrients.blade.php -->
<!-- product_macronutrients -->
#php($macronutrients = isset($entry) ? $entry->macronutrients : false)
<div #include('crud::inc.field_wrapper_attributes') >
#include('crud::inc.field_translatable_icon')
<div class="array-container form-group">
<table class="table table-bordered table-striped m-b-0">
<thead>
<tr>
<th class="text-center">{{-- <i class="fa fa-trash"></i>--}} </th>
#foreach( $field['columns'] as $column )
<th style="font-weight: 300!important;">
// l10n strings (productscatalog::labels.proteins, productscatalog::labels.fats and so on)
#lang("productscatalog::labels.$column")
</th>
#endforeach
</tr>
</thead>
<tbody ui-sortable="sortableOptions" class="table-striped">
<tr class="array-row">
<td>
<p><b>#lang("productscatalog::labels.macrontr")</b></p>
</td>
#foreach( $field['columns'] as $column)
<td>
<input
class="form-control input-sm"
type="text"
name="{{ $column }}"
value="{{ old($column) ? old($column) : $macronutrients ? $macronutrients->$column : '' }}"
#include('crud::inc.field_attributes')
/>
</td>
#endforeach
</tr>
</tbody>
</table>
</div>
</div>
And ProductCrudController:
public function setup()
{
// other stuff...
$this->crud->addField([
'label' => 'Macronutrients',
'type' => 'product_macronutrients',
'name' => '',
'columns' => [
'proteins',
'fats',
'carbons',
'calories',
],
]);
}
public function store(StoreRequest $request)
{
$redirect_location = parent::storeCrud($request);
$this->storeOrUpdateMacronutrients($request, $this->crud->entry);
return $redirect_location;
}
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
$this->storeOrUpdateMacronutrients($request, $this->crud->entry);
return $redirect_location;
}
public function destroy($id)
{
$this->destroyMacronutrients($id);
$return = parent::destroy($id);
return $return;
}
protected function storeOrUpdateMacronutrients(Request $request, Product $product)
{
$macronutrients = Macronutrients::firstOrNew(['id' => $product->id]);
$macronutrients->proteins = $request->input('proteins');
$macronutrients->fats = $request->input('fats');
$macronutrients->carbons = $request->input('carbons');
$macronutrients->calories = $request->input('calories');
$macronutrients->save();
}
protected function destroyMacronutrients($productId)
{
$macronutrients = Macronutrients::findOrFail($productId);
$macronutrients->delete();
}
Hope it helps.
$this->crud->addColumn([
// 1-n relationship
'label' => "Country name", // Table column heading
'type' => "select",
'name' => 'country_name', // the column that contains the ID of that connected entity;
'entity' => 'country', // the method that defines the relationship in your Model
'attribute' => "country_name", // foreign key attribute that is shown to user
'model' => "App\Models\Country",
]);
this is an example for 1-n relationship in laravel backpack
I can upload a image and see the image in storage/app/(abc.jpg)
and set the 'root' => storage_path('app'), in filesystems.php
account.blade.php
<img src="{{ route('account.image', ['filename' => $user->user_id . '.jpg']) }}" alt="" class="img-responsive">
routes.php
Route::get('/userimage/{filename}', [
'uses' => 'UserController#getUserImage',
'as' => 'account.image'
]);
Controller
public function getUserImage()
{
$file = Storage::disk('local')->get($filename);
return new Response($file, 200);
}
GET
http://localhost:8000/userimage/00bea23ff9dd07e5b175c0f8a9283ca8.jpg
500 (Internal Server Error)
In your controller method you need to define $filename like this...
public function getUserImage($filename)
i am using Yii2 and Kartik's FileInput extension and I have successfully get the file uploads working(only single upload). My problem now is that, I get the error as in the title(with logs attached) if I did not choose any files(It should be optional).
After much searching over the internet, I think it has to be something to do with array, but I am not sure how to fix that, especially even with the logs pointing to the exact line!
Here is my log,
Here is my model,
namespace app\models;
use Yii;
class FormMovement extends \yii\db\ActiveRecord
{
public $file;
public static function tableName()
{
return 'form_movement';
}
public function rules()
{
return [
[['fm_date_received', 'fm_form_name', 'fm_from', 'fm_ptj'], 'required'],
[['form_id'], 'integer'],
[['fm_date_received', 'fm_date_action1', 'fm_date_action2','fm_upload'], 'safe'],
[['fm_form_name', 'fm_note'], 'string', 'max' => 500],
[['fm_from', 'fm_ptj', 'fm_action1', 'fm_action2'], 'string', 'max' => 100],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions'=>'jpg,pdf,png,doc,docx,xls,xlsx, jpeg', 'maxFiles' => 3],
];
}
My controller function, the log shows that it is at the line 75, which is this one,
$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;
Been tinkering with it, but no success.
public function actionCreate()
{
$model = new FormMovement();
if ($model->load(Yii::$app->request->post())) {
//set the file name
$fileName = $model -> fm_form_name;
//get instance
$model->file = UploadedFile :: getInstance($model, 'file');
//set the file path in the db
$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;
//save the file to the server directory
$model->save();
$model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);
return $this->redirect(['view', 'id' => $model->form_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Finally my view,
<div class="form-group kv-fieldset-inline">
<?= Html::activeLabel($model, 'file[]', [
'label'=>'MUAT NAIK FAIL',
'class'=>'col-sm-1 control-label'
]) ?>
<div class="col-sm-8">
<?= $form->field($model, 'file',[
'showLabels'=>false
])->widget(FileInput::classname(), [
'options' => ['accept' => 'file/*', 'multiple' => 'true'],
'pluginOptions'=>[
'showUpload' => false,
]
]) ?>
</div>
</div>
This part should be refactored:
//set the file name
$fileName = $model -> fm_form_name;
//get instance
$model->file = UploadedFile :: getInstance($model, 'file');
//set the file path in the db
$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;
//save the file to the server directory
$model->save();
$model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);
like this:
$model->file = UploadedFile::getInstance($model, 'file');
$model->save();
if ($model->file) {
$model->fm_upload = "uploads/{$model->fm_form_name}.{$model->file->extension}";
$model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");
}
Also note that you don't handle failed validation in your controller at all.
For further refactoring, this line:
$model->file = UploadedFile::getInstance($model, 'file');
can be moved to beforeValidate() event handler.
This part:
if ($model->file) {
$model->fm_upload = "uploads/{$model->fm_form_name}.{$model->file->extension}";
$model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");
}
can be moved to afterSave() event handler to keep your controller slim.
In saveAs() it's better to use alias, I desribed it in this answer.