2017-10-02 3 views
0

약간의 문제가 있습니다. Laravel 프로젝트에 유효성 검사 (Try and Catch)를 추가하려고합니다. 문제는 일부 컨트롤러에서는 문제가 없다는 것입니다. 특정이 작동하지 않는 경우, 유효성 검사가 페이지를로드하려고 시도 할 때 무언가 잘못되어 응용 프로그램이 사용자를 메시지가있는 다른 안정적인 페이지로 리디렉션합니다. 여기에 내 코드입니다 :시도해보고 laravel이 저를 위해 작동하지 않습니다

당신이 볼 수 있듯이
public function info($id) 
{ 
    try { 
     $likes = $this->interactionAndUser($id)[0]; 
     $dislikes = $this->interactionAndUser($id)[1]; 
     $downloads = $this->interactionAndUser($id)[4]; 
     $favorite = $this->interactionAndUser($id)[5]; 
     $myLike= $this->interactionAndUser($id)[2]; 
     $myDisLike = $this->interactionAndUser($id)[3]; 
     $book = $this->interactionAndUser($id)[6]; 
     $fileExistEpub = $this->interactionAndUser($id)[9]; 
     $fileExistPdf = $this->interactionAndUser($id)[10]; 
     $books = Book::find($id); 
     $forum = Forum::where('book_id', $id)->first(); 
     $forumId = $forum->id; 
     $forumTheme = $forum->theme_id; 
     $forumHasTheme = Theme::where('id', $forumTheme)->first(); 
     $comments = Comment::where(['forum_id' => $forumId, 'comment_id' => null]) 
     ->paginate(5); 
     if(Cache::has($id)==false) { // Si el ID tiene un valor falso o 0 para el cache, agregue 1 
      Cache::add($id, 'contador', 0.05); // Cada 0.05 segundos se contara una nueva visita por usuario, que recargue la pagina 
      $book->views+=1; 
      $book->save(); 
     } 
     return view('books/info', compact('books', 'book', 'likes', 'dislikes', 'favorite', 'downloads', 'myLike', 'myDisLike', 'forum', 'forumHasTheme', 'comments', 'fileExistEpub', 'fileExistPdf')); 
    } catch (\Exception $e) { 
     return redirect('books')->with('errors', 'Ha ocurrido un errror, lo sentimos'); 
    } 
    } -> This code work perfectly 

는 Laravel의 예외의 간단한 검증이다, 이것은 뭔가 잘못된 경우, 사용자가 다른 안정 페이지로 리디렉션 될 것입니다, 잘 작동,이 코드 조각이다 BookController라는 컨트롤러에서 문제는 FrontController에서 발생하며 다른 함수는 유효성 검사를 통과 할 때 사용자를 안정된 페이지로 리디렉션하지 않습니다. 여기에 내 코드

public function info_novelty($id) 
    { 
    try { 
     $novelty = Novelty::find($id); 
     return view('news.show', compact('novelty')); 
    } catch (\Exception $e) { 
     return redirect('noticias')->with('errors', 'Ha ocurrido un errror, lo sentimos'); 
    } 
    } -> This validation doesn't work 

이 일어나는 이유는 누군가가 나를 도울 수 있다면, 나는

정말 gratefull있을거야 모르는 그리고 이것은 내가 그것을

있어 오류입니다 비 개체의 속성을 얻으려고 노력 (보기 : /home/vagrant/Code/Biblio/resources/views/news/show.blade.php)

답변

1

당신은 보장하기 위해 findOrFail() 방법을 사용할 수 있습니다 주어진 id에 대해 자원을 찾을 수 없으면 예외가 발생합니다.

어떤 자원이 발견되지 않는 경우

findOrFail() 방법은 ModelNotFoundException을 던질 것이다, 그래서 당신의 코드는 특별히 찾아보실 수 있습니다 :

당신은 영웅, 사람이야
try { 
     $novelty = Novelty::findOrFail($id); 
     return view('news.show', compact('novelty')); 
    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { 
     // return more specific error message 
    } catch (\Exception $e) { 
     return redirect('noticias')->with('errors', 'Ha ocurrido un errror, lo sentimos'); 
    } 
+0

, 덕분에 많이! –

관련 문제