error in Laravel 5.4 resource controller using various methods - php

I created a NotesController with php artisan command
php artisan make:controller NoteController --resource
Route
Route::resource('notes','NoteController');
I checked them using route:list command too. All route exists.
But when I try to send the form to notes.store it gets redirected to localhost/blog/notes/ and shows
Index of localhost/blog/public/notes/
[ICO] Name Last modified Size Description
[PARENTDIR] Parent Directory -
Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/7.0.9 Server at localhost Port 80
Create form is
{!! Form::open(['method' => 'POST', 'route' => 'notes.store', 'class' => 'form-horizontal']) !!}
{!! Form::hidden('user_id', Auth::user()->id) !!}
{!! Form::label('level', 'Level') !!}
{!! Form::select('level', $level,null, ['class' => 'form-control', 'required' => 'required']) !!}
{!!Form::label('faculty','Faculty:')!!}
{!!Form::text('faculty',null, array('class'=> 'form-control'))!!}
{!! Form::label('notecatagory', 'Note Catagory') !!}
{!! Form::select('notecatagory', $notecatagory,null, ['class' => 'form-control', 'required' => 'required']) !!}
{!!Form::label('title','Title:')!!}
{!!Form::textarea('title',null, array('class'=> 'form-control'))!!}
<div class="btn-group pull-right">
{!! Form::submit("Create Post", ['class' => 'btn btn-block btn-success', 'style'=>'margin-top : 20px;margin-bottom: 20px;']) !!}
</div>
{!! Form::close() !!}
I manually entered and checked data notes.show and notes.update works properly but I have problem with notes.index and notes.store I have other posts controller which works fine. I tried editing posts controller but problem is still the same
Note Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Relations\Relation;
use Session;
use App\Note;
use
App\User;
class NoteController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('notes.index');
}
public function store(Request $request)
{
$this->validate($request, array(
'user_id'=> 'required |number',
'level'=>'required',
'faculty'=>'required',
'notecatagory'=>'required',
'title'=> 'required'
));
$note = new Note;
$note->user_id = $request->user_id;
$note->level = $request->level;
$note->faculty = $request->faculty;
$note->notecatagory = $request->notecatagory;
$note->title = $request->title;
$note->save();
Session::flash('success','Note successfully created');
return redirect()->route('notes.show', $note->id);
}

I don't know what is wrong in laravel. After trying all day, I made some changes in route and it started working.
I changed the route from
Route::resource('notes','NoteController');
to
Route::resource('note','NoteController');
and changed folder name from notes to note and all other routes to note.index note.store . Without any other changes the same files started working. I still don't know what happened. If you know please let me know

Related

always return null while uploading file to laravel 7

I'm having an issue while uploading file to laravel either its pdf or image always return to null
This is the View
{!! Form::open(['action' => 'TransactionInController#store', 'method' => 'POST', 'autocomplete' => 'off',
'class' => 'form-horizontal', 'enctype' => 'multipart/form-data']) !!}
<div class="row">
{{ Form::label('Device Document', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="col-sm-7">
{{ Form::file('device_document') }}
<p style="color: red;">#error('device_document') {{ $message }} #enderror</p>
</div>
</div>
{!! Form::close() !!}
and this is the Controller i use
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$imageName = $request->input('device_document');
$request->image->move(public_path('document-image'), $imageName);
$transactionsin->save();
return redirect('/transactionsin');
}
i know its been asked before and i already try several way to upload file this error.
This is the error message i get while running the code
Call to a member function move() on null
but if i change the code in controller into something more simple like this
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$transactionsin->device_document = $request->input('device_document');
$transactionsin->save();
return redirect('/transactionsin');
}
it will not return any error message but it will saved as null in the database.
Use $request->file('device_document') instead of input method to catch a file.
If you would like to get original name of the uploaded file, you may do so using the getClientOriginalName() method
Try this :
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$imageName = $request->file('device_document');
$imageName->move(public_path('document-image'), $imageName->getClientOriginalName());
$transactionsin->device_document = $request->file('device_document')->getClientOriginalName();
$transactionsin->save();
return redirect('/transactionsin');
}
See the official documentation here
you can access file using file() method not input method and after upload image to get image path using asset() function like this below code
$transactionsin = new TransactionIn;
$image= $request->file('device_condition');
//upload imaage
$image->move(public_path('document-image'), $image->getClientOriginalExtension());
//asset() function use store path
$transactionsin->device_document = asset('document-image/'.$image->getClientOriginalExtension());
$transactionsin->save();

Trying to get property of non-object laravel when accessing database

I am trying to code the edit route for laravel and for some reason keep getting the error "Trying to get property of non-object laravel". The Create controller works fine, however when I use the controller#update route I keep getting this error
My Controller for adding an event: (update)
public function update(Request $request, $id)
{
//create event
$my_user = my::find($id);
$my_user->programme = $request->input('programme');
$my_user->goal1 = $request->input('goal1');
$my_user->goal2 = $request->input('goal2');
$my_user->goal3 = $request->input('goal3');
$my_user->goal4 = $request->input('goal4');
$my_user->goal5 = $request->input('goal5');
$my_user->user_id = auth()->user()->id;
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
edit page
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Post</h1>
{!! Form::open(['action' => ['myUserController#update', $my_user], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Event Name')}}
{{Form::text('goal1', $my_user->goal1, ['class' => 'form-control', 'placeholder' => 'Goal One'])}}
</div>
{{Form::hidden('_method','PUT')}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Given that you are using a Route::resource you can type-hint your parameters by writing something like
public function update(Request $request, MyUser $myuser){
// The $myuser parameter comes from the Route::resource and can be verified using php artisan route:list in your terminal
// edit $my_user
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
Update after reviewing LaravelCollective documentation for Form
Thank you Sohel0415 for mentioning that you do not need to call $my_user->id for providing the route parameter with the Form facade.
You can use this method on your code:
{{ Form::open(array('url'=>'admin/users/store' , 'method' =>'POST')) }}
and your route define by this method in web.php file:
Route::post('users/store', 'admin\UserController#store');

laravel 5 won't delete files from storage section

when I try to delete specific file trough my controller I get an error
Sorry, the page you are looking for could not be found.
NotFoundHttpException
This is my controller:
public function destroyFile($file_name)
{
$file = storage_path('documents').'/'.$file_name;
Storage::delete($file);
return redirect('/documents');
}
My route:
Route::delete('documents/{file}','FilesController#destroyFile');
And my view:
{!! Form::open(['method' => 'DELETE', 'action' => ['FilesController#destroyFile', $file->name] ]) !!}
{!! Form::hidden('_method', 'DELETE') !!}
{!! Form::token() !!}
{!! Form::submit(trans('buttons.del-cat'),['class'=>'btn btn-danger user-delete push-right']) !!}
{!! Form::close() !!}
I had the same problem, everything was set right but it still didn't work.
Instead of Storage::delete() I used File::delete(), that fixed it.
Hope this works!
public function images(Request $request,$id){
$user_id=$request->session()->get('user_id');
$data=DB::table('company_images')->where('id',$id)->first();
//deleteing the image from database and server
DB::table('company_images')->where('id', '=', $id)->delete();
//delete the image form the server
$path=public_path("/assets/img/company/$data->image");
unlink($path);
return redirect("/company/$user_id/add_details")->with('delete','delete');
}
this is function i used to delete company images using unlink($path) this works well with me also the big note:you should write carefully the path to file you delete.
You must set public in filesystem.php :
'default' => env('FILESYSTEM_DRIVER', 'public')
instead of :
'default' => env('FILESYSTEM_DRIVER', 'local')
change local to public.

How to customize a field of the model before storing in database

I have a model like this :
class Article extends Model {
protected $fillable = [
'title',
'body',
'img_profile', // store name of image
];
}
And a controller like this:
public function store(ArticleRequest $request){
$article = Auth::user()->articles()->create($request->all());
return redirect('articles');
}
And a form like this:
{!! Form::model($article = new \App\Article,['url' => 'articles','files' => true ]) !!}
{!! Form::text('title', null ) !!}
{!! Form::textarea('body', null) !!}
{!! Form::file ('img_profile', '') !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
When I submit the form, the img_profile field is stored default cached file which is /private/var/tmp/phpceBMP2.But I just want to update file_name in img_profile.
How can I change the value of the img_profile request before storing it in database?
You should use mutator for Article model this way:
public function setImgProfileAttribute($value)
{
$this->attributes['img_profile'] = '/private/var/tmp/phpceBMP2/'. $value;
}
However you should think if you really want to store the path in DB this way. What if you will want to change it in future? You will have to update all the records?

Laravel conflicting routes

My routes.php excerpt:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
});
My PostsController.php excerpt:
/**
* DELETE /admin/posts/{id}
*/
public function destroy($id)
{
// code
}
/**
* DELETE /admin/posts/trash
*/
public function emptyTrash()
{
// code
}
The problem is that Laravel confuses the 'trash' string in a DELETE /admin/posts/trash request as an {id} parameter. As a consequence, the destroy() method is called instead of emptyTrash(). Why and What can I do for this?
Firstly, order matters. Laravel will search the routes for a match in the order you register them. As you figured out, Laravel will take trash as an id and therefore the URI matches the resource route. Since that route is registered before your additional one, it will use the resource route.
The simplest fix is to just change that order:
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
If you don't like that you can try to limit the parameter for your resource route to numbers only. Unfortunately you can't just add a ->where() to the resource route like you could with others.
Instead you have to define a global pattern for the route parameter. The route parameter Route::resource chooses is the resource name (in snake_case).
So this should work for you:
Route::pattern('posts', '[0-9]+');
Somewhere in your view, you should have a button or a link for actually deleting the post. The view should look something like this:
#section('content')
<div class="panel panel-default">
<div class="panel-heading clearfix">
<b>{{ $post->post_name . ' (id:' . $post->post_id . ')' }}</b><br />
<b> {{ link_to_route('overview', 'Go Back To Post List') }} </b>
<div class="pull-right">
// FORM FOR DELETING POST
{{ Form::open(array('route' => array('delete_post', $post->post_id))) }}
{{ link_to_route('edit_post', 'Edit Post', array('id' => $post->post_id), array('class' => 'post_img_button_edit')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete Post', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
<div class="pull-right">
// FORM FOR EMPTYING TRASH
{{ Form::open(array('route' => 'empty_trash')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Empty Trash', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
</div>
/* Additional HTML code within view */
Your controller should be similar to this:
public function destroy($id)
{
$this->post->delete($id);
return \Redirect::route('overview');
}
public function emptyTrash()
{
// code for collecting and emptying Trash
}
And your routes should look similar to this:
Route::delete('admin_posts/admin_posts/{id}/destroy', array('as'=>'delete_post', 'uses'=>'PostsController#destroy'));
Route::delete('posts/trash', array('as'=>'empty_trash', 'uses'=>'PostsController#emptyTrash'));
The name of your route for actually deleting posts be 'delete_post'.
The name of your route for emptying your trash will be empty_trash
Basically you're explicitly defining your routes so that you'll avoid less ambiguity and Laravel will know which routes to take. Hopefully this information will help!

Categories