0

I would like to know which of these 2 patterns would be better:

/photos/123/edit

or

/photos/edit/123

Currently I am using the first, which gives me a Whoops, looks like something went wrong. when I try /photos/123/editxx instead of a 404 not found.

routes:

I am unsure where to look for the mistake, these are the photos routes:

Route::get('photos/randpics','PhotosController@randpics');
Route::get('photos/{id}/edit','PhotosController@getEdit')->middleware(['auth']);
Route::post('photos/{id}/edit','PhotosController@postEdit')->middleware(['auth']);
Route::post('photos/{id}/retag', ['as' => 'photos.retag', 'uses' => 'PhotosController@retag'])->middleware(['auth']);
Route::post('photos/{id}/delete','PhotosController@delete')->middleware(['auth']);
Route::get('photos/{id}/albums', 'PhotosController@getAlbums')->middleware(['auth']);
Route::post('photos/{id}/albums', 'PhotosController@postAlbums')->middleware(['auth']);
Route::get('photos/{id}/detail','PhotosController@detail');
Route::get('photos/{id}','PhotosController@single');
Route::post('photos/like', 'PhotosController@postLike')->middleware(['auth']);
Route::post('photos/unlike', 'PhotosController@postUnlike')->middleware(['auth']);
Route::get('photos','PhotosController@index');

getEdit() and postEdit():

The same error, complaining about an undefined variable in the master layout template appears, when I enter /photos/123/a/a/a/ for example.

public function getEdit(Request $request, $id = null)
{
    $pic = Pic::findOrFail($id);

    if(Gate::denies('edit-pic',$pic)) {
        abort(403);
    }

    $pic->text = htmlspecialchars($pic->text);

    $years = array_combine(range(date("Y"), 1960), range(date("Y"), 1960));

    $location = $pic->location;
    $tags = $pic->tags;
    $tagsarray = $pic->tagNames();
    $albums = $pic->albums;

    $locations = array();
    $getlocations = Location::orderBy('city')->get();
    foreach($getlocations as $gl)
    {
        $locations[$gl->id] = $gl->city.' ('.$gl->country.')';
    }

    $cats = Cat::lists('cat','cat')->all();

    return view('photos.edit',compact('pic','location','tags','tagsarray','albums','locations','cats','years'));
}


public function postEdit(Request $request, $id = null)
{
    $pic = Pic::findOrFail($id);

    if(Gate::denies('edit-pic',$pic)) {
        abort(403);
    }

    $this->validate($request, [
        'title'    => 'max:200',
        'text'     => 'max:3000',
        'location' => 'required|exists:locations,id',
        'cat'      => 'required|exists:cats,cat',
        'jahrprod' => 'date_format:Y'
    ]);

    $pic->title = trim($request->input('title'));
    $pic->text = trim($request->input('text'));
    $pic->jahrprod = ($request->input('jahrprod')) ? $request->input('jahrprod') : null;
    $pic->location_id = $request->input('location');
    $pic->cat = $request->input('cat');
    $pic->save();

    #mail
    $maildata = array(
        'msg' => 'picture '.$id.' ( '.$request->input('title').' ) was edited by '.Auth::user()->username
    );

    Mail::send(['text' => 'emails.empty'], $maildata, function($message){
        $message->to('xx@yy.de')->from('xx@yy.de')->subject('picture edited');
    });

    return back()->with('success','photo information updated');
}

Controller.php

It seems, with more than 2 URL segments, the Controller.php is not working properly. /domain.xy/1/2 shows the 8 but /domain.xy/1/2/3 throws the error Undefined variable: photos_online

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

use Auth;
use Cache;
use DB;

use App\Pic;
use App\Upload;

use Carbon\Carbon;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        dd(8);
        //.......
    }
}
unor
  • 92,415
  • 26
  • 211
  • 360
haheute
  • 2,129
  • 3
  • 32
  • 49
  • 2
    Are you asking the opinionated "which practice is better" or "Why isn't the practice I chose working?" – dckuehn Jul 19 '16 at 13:13
  • 1
    Well, the 1st is better, but the error has nothing in common with "which url pattern is better" question – Marcin Nabiałek Jul 19 '16 at 13:13
  • I thought there could be a 'best practice' – haheute Jul 19 '16 at 13:15
  • 1
    Like @MarcinNabiałek said, I agree the first option is the "best practice", and as that is what you're using, the error is a result of your implementation. – dckuehn Jul 19 '16 at 13:18
  • Can you show your getEdit and postEdit functions in your PhotoController? – theMohammedA Jul 19 '16 at 13:46
  • You said `/photos/123/editxx` give you error but does `/photos/123/edit` works? – theMohammedA Jul 19 '16 at 14:09
  • yes. also `/a` gives me a 404 but `/a/b/c` gives the same error. as if too many segments would be a problem with the 404 page. – haheute Jul 19 '16 at 14:21
  • 1
    See your program will give error to all odd urls or to the urls that is not mentioned in the router. So your problem is you wanna redirect all errors to 404 right? – theMohammedA Jul 19 '16 at 14:56
  • I have a 404 error page but it does not work if the URL segment is missing. So if the route is `/trees/a/b`, `/trees/a/xxxx` will perhaps throw 404 , but `/trees/a/b/c/xxxxxx` does show a strange error about missing variables. It should say "page not found". I don't really understand what is going on. – haheute Jul 19 '16 at 15:02
  • what is the default behaviour of laravel when I enter a not defined route? like `/1/2/3/4/5` or so – haheute Jul 19 '16 at 15:08
  • What exception you exactly get? is it `NotFoundHttpException`? – theMohammedA Jul 19 '16 at 15:13
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117728/discussion-between-haheute-and-themohammeda). – haheute Jul 19 '16 at 15:15

1 Answers1

1

If you follow laravel's resource controller guidelines https://laravel.com/docs/5.2/controllers#restful-resource-controllers

You should go with the first one.

But to fix your problem show us your route and controller function handling it.

Update

open AppServiceProvider located in app/http/providers and replace boot() function with this

public function boot()
{
    //initilizw $photos_online
    $photos_online = Cache::rememberForever('index_countpics', function() 
    { 
        return Pic::count(); 
    }); 

    #pics today 
    if (Cache::has('pics_today')){ 
        $pics_today = Cache::get('pics_today'); 
    }else{ 
        $pics_today = Pic::whereRaw('DATE(created_at) = DATE(NOW())')->count(); 
        Cache::put('pics_today', $pics_today, Carbon::tomorrow()); 
    } 

    # count waiting uploads 
    $waiting_uploads = Cache::rememberForever('waiting_uploads', function() 
    { 
        return Upload::where('accepted',0)->where('infos',1)->count(); 
    }); 

    # user online 
    $client_ip = request()->ip(); 

    $check = DB::table('useronline')->where('ip', $client_ip)->first(); 

    $username = (Auth::guest()) ? null : Auth::user()->username; 
    $displayname = (Auth::guest()) ? null : Auth::user()->displayname; 

    if(is_null($check)){ 
        DB::table('useronline')->insert(['ip' => $client_ip, 'datum' => DB::raw('NOW()'), 'username' => $username, 'displayname' => $displayname]); 
    }else{ 
        DB::table('useronline')->where('ip', $client_ip)->update(['datum' => DB::raw('NOW()'), 'username' => $username, 'displayname' => $displayname]); 
    } 

    DB::delete('DELETE FROM useronline WHERE DATE_SUB(NOW(), INTERVAL 3 MINUTE) > datum'); 

    $users_online = DB::table('useronline')->whereNotNull('username')->get(); 
    $guests_online = DB::table('useronline')->count(); 

    #unread messages 
    $unread_messages = 0; 
    if(Auth::check()){ 
        $unread_messages = Auth::user()->newThreadsCount(); 
    } 

    view()->share('photos_online',$photos_online); 
    view()->share('pics_today',$pics_today); 
    view()->share('waiting_uploads',$waiting_uploads); 
    view()->share('users_online',$users_online); 
    view()->share('guests_online',$guests_online); 
    view()->share('unread_messages',$unread_messages);
}
theMohammedA
  • 677
  • 7
  • 11