Moving photos between albums
Moving photos between albums is a great feature for managing the album’s images. Many photo gallery systems come with this feature. So, we can code it easily with Laravel. We need a form and controller function for adding this feature to our photo gallery system. Let’s code the controller function first. Open the ImagesController.php
file which is located in app/http/controllers/
and add the following code in it:
public function postMove() { $rules = array( 'new_album' => 'required|numeric|exists:albums,id', 'photo'=>'required|numeric|exists:images,id' ); $validator = Validator::make(Input::all(), $rules); if($validator->fails()){ return Redirect::route('index'); } $image = Image::find(Input::get('photo')); $image->album_id = Input::get('new_album'); $image->save(); return Redirect::route('show_album',array('id'=>Input::get('new_album'))); }
As you can see in the preceding code, we use the Validation
class again. Let’s examine the rules. The first rule is as follows:
'new_album' => 'required|numeric|exists:albums,id'
The preceding rule means that the new_album
field is required
(must be posted in the form), must be a numeric value, and exist in the id
column of the albums
table. We want to assign images to albums, so the images must exist. The second rule is as follows:
'photo'=>'required|numeric|exists:images,id'
The preceding rule means that the photo
field is required
(must be posted in the form), must be a numeric value, and exist in the id
column of the images
table.
After successful validation, we update the album_id
column of the photos
field and redirect the browser to show the new album of photos using the following code:
$image = Image::find(Input::get('photo')); $image->album_id = Input::get('new_album'); $image->save(); return Redirect::route('show_album',array('id'=>Input::get('new_album')));
The final code of the Images
controller should be as follows:
<?php class ImagesController extends BaseController{ public function getForm($id) { $album = Album::find($id); return View::make('addimage') ->with('album',$album); } public function postAdd() { $rules = array( 'album_id' => 'required|numeric|exists:albums,id', 'image'=>'required|image' ); $validator = Validator::make(Input::all(), $rules); if($validator->fails()){ return Redirect::route('add_image',array('id' =>Input::get('album_id'))) ->withErrors($validator) ->withInput(); } $file = Input::file('image'); $random_name = str_random(8); $destinationPath = 'albums/'; $extension = $file->getClientOriginalExtension(); $filename=$random_name.'_album_image.'.$extension; $uploadSuccess = Input::file('image')->move($destinationPath, $filename); Image::create(array( 'description' => Input::get('description'), 'image' => $filename, 'album_id'=> Input::get('album_id') )); return Redirect::route('show_album',array('id'=>Input::get('album_id'))); } public function getDelete($id) { $image = Image::find($id); $image->delete(); return Redirect::route('show_album',array('id'=>$image->album_id)); } public function postMove() { $rules = array( 'new_album' => 'required|numeric|exists:albums,id', 'photo'=>'required|numeric|exists:images,id' ); $validator = Validator::make(Input::all(), $rules); if($validator->fails()){ return Redirect::route('index'); } $image = Image::find(Input::get('photo')); $image->album_id = Input::get('new_album'); $image->save(); return Redirect::route('show_album',array('id'=>Input::get('new_album'))); } }
Our controller is ready, so we need to set up the updated form’s route in app/routes.php
. Open the file and add the following code:
Route::post('/moveimage', array('as' => 'move_image', 'uses' => 'ImagesController@postMove'));
The final code located in app/http/routes.php
should look as follows:
<?php Route::get('/', array('as' => 'index', 'uses' => 'AlbumsController@getList')); Route::get('/createalbum', array('as' => 'create_album_form', 'uses' => 'AlbumsController@getForm')); Route::post('/createalbum', array('as' => 'create_album', 'uses' => 'AlbumsController@postCreate')); Route::get('/deletealbum/{id}', array('as' => 'delete_album', 'uses' => 'AlbumsController@getDelete')); Route::get('/album/{id}', array('as' => 'show_album', 'uses' => 'AlbumsController@getAlbum')); Route::get('/addimage/{id}', array('as' => 'add_image', 'uses' => 'ImagesController@getForm')); Route::post('/addimage', array('as' => 'add_image_to_album', 'uses' => 'ImagesController@postAdd')); Route::get('/deleteimage/{id}', array('as' => 'delete_image', 'uses' => 'ImagesController@getDelete')); Route::post('/moveimage', array('as' => 'move_image', 'uses' => 'ImagesController@postMove'));
Creating an update form
Now we need to create our update form in our template file. Open the template file which is located inapp/views/ album.blade.php
and change the foreach
loop as follows:
@foreach($album->Photos as $photo) <div class="col-lg-3"> <div class="thumbnail" style="max-height: 350px;min-height: 350px;"> <img alt="{{$album->name}}" src="/albums/{{$photo->image}}"> <div class="caption"> <p>{{$photo->description}}</p> <p>Created date: {{ date("d F Y",strtotime($photo->created_at)) }}at {{ date("g:ha",strtotime($photo->created_at)) }}</p> <a href="{{URL::route('delete_image',array('id'=>$photo->id))}}" onclick="returnconfirm('Are you sure?')"><button type="button"class="btn btn-danger btn-small">Delete Image</button></a> <p>Move image to another Album :</p> <form name="movephoto" method="POST"action="{{URL::route('move_image')}}"> <select name="new_album"> @foreach($albums as $others) <option value="{{$others->id}}">{{$others->name}}</option> @endforeach </select> <input type="hidden" name="photo"value="{{$photo->id}}" /> <button type="submit" class="btn btn-smallbtn-info" onclick="return confirm('Are you sure?')">Move Image</button> </form> </div> </div> </div> @endforeach
Wrapping up
In this article, we’ve created a simple photo gallery system with Laravel’s built-in functions and the Eloquent database driver. We’ve learned how to validate the data, and about the powerful data relation method in Eloquent named hasMany. In the next coming articles , we’ll learn to work with more complex tables, and relational data and relation types.
hope you will like it :)
the syntax highlighting is not showing correctly
sorry for late reply ! can you please tell me where is not showing correctly ?
may be this ” & gt; ” it showing instead of ” > “
ok thanks i will fix it
thanks i have fixed that ! i am now just using pre tag simple solution :)
Hello
I have gone with the creation of this project one line at a time, I chose to name the model (Image) rather than (Photos) to be consistent, and I get this error
BadMethodCallException in Builder.php line 1999:
Call to undefined method IlluminateDatabaseQueryBuilder::Image()
when I try to track it, it ends in this line:
$albums = Album::with(‘Photos’)->get();
return View::make(‘index’)
->with(‘albums’,$albums);
I tried to name it with(appImage) but no luck, can you help me out please?
by the way, you’re doing an excellent job there, thanks so much.
Hello, thanks for this fine tutorial. However, it seems not to fit to the Laravel 5.1 directory structure. Is there an update ?
i will upadate it as soon as possible ! now busy in projects :(
Command will generate a migration file underapp/database/migrations CMD:php artisan make:migration create_albums_table –create=albums –table
sorry but what’s your point here ?
Over all its the good tutorial for beginners… I think you have to double check your commands before posting…Thats the point …
ok thanks ! will be doing from next time !
agree it does not say how to create a migration, beginners won’t understand how to create a migration
thanks for the album gallery laravel project. I think there is Albums Object missing in :
Albumscontroller::getAlbum($id)
and view: album.blade.php where you foreach through the object albums as others.
you are not providing the obj. albums in Albumscontroller::getAlbum($id).
let me see that btw ! thanks 4 pointing it out
How did you solve that ?
public function getAlbum($id)
{
$data[‘album’] = $this->album->with(‘Photos’)->find($id);
$data[‘albums’] = $this->album->all();
return view(‘album’)->with($data);
}
Obs. I’m using depency injection on __construct(). if u dont replace $this->album to Album::
open up your terminal, navigate through your project folder, and run the following command: “where is the command ?”
you are missing this command “php artisan make:migration create_albums_table”
Please, can you send me the source code? [email protected]
The code is included in the tutorial.
I have this error when I want to create an album
TokenMismatchException in VerifyCsrfToken.php line 67:
Add this to your form..
Great tutorial. Have you uploaded the code anywhere?
So many derelict Laravel tutorials out there.
It would be faster just to make a pivot table from albums and photos.
Second thing, if you are talking about albums and photos in plural, than update this tutorial to show people how to upload multiple images, not just one.
And third thing… we have Laravel 5.3 now ;)
i have an error
ErrorException in d17e4d0327979a8a446079b4be560aa37d15c74a.php line 66:
Undefined variable: albums (View: album.blade.php)
Please Help. Class ‘BaseController’ not found
Thank you very much!
I could adapt it to laravel 5.4 without problems
Can you to published in version 5.4?
Sure, Here: https://github.com/YouDevs/Gallery-System-Laravel-5.4
Hello everyone,
I am looking to create a Photo Gallery in the employer I already installed and that works well.
For this gallery I followed the following tutorial:
https://dunebook.com/tutorial-creating-a-photo-gallery-system-with-laravel/
But I find myself with a mistake and also can not open the link of the function.
“Whoops, looks like something went wrong. 1/1 FatalErrorException in Handler.php line 25: Uncaught TypeError: Argument 1 passed to AppExceptionsHandler::report() must be an instance of Exception, instance of Error given, called in /home/www/test.com/laravel/vendor/compiled.php on line 1720 and defined in /home/www/test.com/laravel/app/Exceptions/Handler.php:25 Stack trace: #0 /home/www/test.com/laravel/vendor/compiled.php(1720): AppExceptionsHandler->report(Object(Error)) #1 [internal function]: IlluminateFoundationBootstrapHandleExceptions->handleException(Object(Error)) #2 {main} thrown 1. in Handler.php line 25”
And I do not understand how to correct that.
Thanks to your helpers,
You say to put the first controller in:
app/http/controllers/
and the second one in:
app/controllers/
shouldn’t the controllers go in one place?
On the second page you write to out the ImageController (singular) to app/controler, then oon the third page you write to “Open the ImagesController.php file which is located in app/http/controllers/” but firstly there’s no controller there, and secondly is that supposed to be ImageControler (singular) or ImagesControler (plural)?