hello everyone I have a big problem in the show function. I do not know what the problem is .. I get this error "Trying to get property 'id' of non-object"
ConversationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Repository\ConversationRepository;
use Illuminate\Auth\AuthManager;
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository, AuthManager $auth){
$this->r= $conversationRepository;
$this->auth=$auth;
}
public function index () {
return view('conversations/index' , ['users'=> $this->r->getConversations($this->auth->user()->id)]);
}
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
}
public function store(User $user){
$this->r->createMessage(
$request->get('content'),
$this->auth->user()->id,
$user->id
);
return redirect(route('conversations.show', ['id'=> $user->id]));
}
}
?>
web.php
<?php
//use Illuminate\Routing\Route;
//use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'ConversationsController#index')->name('home');
Route::get('/conversations', 'ConversationsController#index')->name('conversations');
Route::get('/conversations/{user}', 'ConversationsController#show')->name('conversations.show');
Route::post('/conversations/{user}', 'ConversationsController#store');
enter image description hereConversationRepository.php
<?php
namespace App\Repository;
use App\User;
use App\Message;
class ConversationRepository {
private $user;
private $message;
public function __construct(User $user, Message $message){
$this ->user = $user;
$this->message= $message;
}
public function getConversations(int $userId){
return $this->user->newQuery()
->select('name', 'id')
->where('id', '!=', $userId)
->get();
}
public function createMessage (string $content, int $from, int $to){
return $this->message->newQuery()-> create([
'content' => $content,
'from_id' => $from,
'to' => $to,
'created_at' => Carbon::now()
]);
}
}
?>
the problem in this function
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
more precisely in this line
'users'=> $this->r->getConversations($this->auth->user()->id)
And thanks ..
Try using $this->auth()->user()->id instead. Also the routes accessing auth should be enclosed within the web middleware.
Related
I have a problem that I can not resolve in Laravel 5.4.
I'm using the Postman extension to make requests for my API, so far it works normally with GET, but when I try to do a POST, the method that's actually called is GET again. (The API can not have authentication or token for the user).
api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['api' => ['auth:api']], function(){
Route::group(['prefix' => 'user'], function(){
Route::get('{id}', ['uses' => 'UserController#getUser']);
Route::post('', ['uses' => 'UserController#saveUser']);
Route::get('', ['uses' => 'UserController#allUsers']);
Route::put('{id}',['uses' => 'UserController#updateUser']);
Route::delete('{id}', ['uses' => 'UserController#deleteUser']);
});
});
UserController.php:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller{
protected $user = null;
public function __construct(User $user){
$this->user = $user;
}
public function allUsers(){
return $this->user->allUsers();
}
public function getUser($id){
}
public function saveUser(){
return $this->user->saveUser();
}
public function updateUser($id){
}
public function deleteUser($id){
}
}
User.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $hidden = ['venda','remember_token', 'created_at','updated_at'];
public $fillable = ['nome','email', 'venda'];
public function allUsers(){
return self::all();
}
public function saveUser(){
$input = Input::all();
echo 'aa';
$user = new User();
$user->fill($input);
$user->save();
return $user;
}
}
First change this:
Route::group(['api' => ['auth:api']], function(){
To:
Route::group(['middleware' => ['auth:api']], function(){
So i have a 'TicketController' which holds my functions for manipulating 'tickets' in a system.
I am looking to work out the best way to send my new route that will take a route parameter of {id} to my TicketController to view a ticket.
Here is my route set
Route::group(['middleware' => 'auth', 'prefix' => 'tickets'], function(){
Route::get('/', 'TicketController#userGetTicketsIndex');
Route::get('/new', function(){
return view('tickets.new');
});
Route::post('/new/post', 'TicketController#addNewTicket');
Route::get('/new/post', function(){
return view('tickets.new');
});
Route::get('/view/{id}', function($id){
// I would like to ideally call my TicketController here
});
});
Here is my ticket controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Ticket;
use App\User;
class TicketController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Returns active tickets for the currently logged in user
* #return \Illuminate\Http\Response
*/
public function userGetTicketsIndex()
{
$currentuser = \Auth::id();
$tickets = Ticket::where('user_id', $currentuser)
->orderBy('updated_at', 'desc')
->paginate(10);
return view('tickets.index')->with('tickets', $tickets);
}
public function userGetTicketActiveAmount()
{
$currentuser = \Auth::id();
}
public function addNewTicket(Request $request)
{
$this->validate($request,[
'Subject' => 'required|max:255',
'Message' => 'required|max:1000',
]);
$currentuser = \Auth::id();
$ticket = new Ticket;
$ticket->user_id = $currentuser;
$ticket->subject = $request->Subject;
$ticket->comment = $request->Message;
$ticket->status = '1';
$ticket->save();
}
public function viewTicketDetails()
{
//retrieve ticket details here
{
}
You don't need to use closure here. Just call an action:
Route::get('/view/{id}', 'TicketController#showTicket');
And in TicketController you'll get ID:
public function showTicket($id)
{
dd($id);
}
More about this here.
You should use type-hint in laravel. Its awesome
In route
Route::get('/view/{ticket}', 'TicketController#viewTicketDetails');
In controller
public function viewTicketDetails(Ticket $ticket)
{
//$ticket is instance of Ticket Model with given ID
//And you don't need to $ticket = Ticket::find($id) anymore
{
I am totally new in laravel.
I install laravel 5.2 . I have done with CRUD in laravel. Now i want to integrate laravel authentication package. so i choose zizaco\entrust.
I follow each steps from doc link. but i don't understand what is wrong. In doc there is not mentioned that in which file i have to add following code.
$owner = new Role();
$owner->name = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description = 'User is the owner of a given project'; // optional
$owner->save();
$admin = new Role();
$admin->name = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description = 'User is allowed to manage and edit other users'; // optional
$admin->save();
and other below code in document.
Even
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
Not mentioned about implements class.
i do
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
but i got error
Trait 'App\Authenticatable' not found
New learner can't get where to place code. i search alot but i can't get perfect document which give right direction.
Where to create role,permissions? Anyone please help me.
1.Install "zizaco/entrust": "5.2.x-dev"
2.add provider and aliases in app.php
3.php artisan vendor:publish
4.php artisan migrate
Now add in user.php
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword, EntrustUserTrait;
}
Next Create a model for Role
use Zizaco\Entrust\EntrustRole
class Role extends EntrustRole
{
protected $table = 'roles';
protected $fillable = ['name', 'display_name', 'description']
}
Now create a model for permmission
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
protected $table = 'permissions';
protected $fillable = ['name', 'display_name', 'description'];
}
Now create a seeding table for roles and permissions
UserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Permission;
use App\Role;
use App\User;
class UserTableSeeder extends seeder
{
public function run()
{
Permission::truncate();
Role::truncate();
User::truncate();
\DB::table('role_user')->delete();
\DB::table('permission_role')->delete();
//create a user
$veeru = User::create([
'name' => 'veeru',
'email' => 'something#something.com',
'password' => bcrypt('qwerty'),
]);
//create a role of admin
$admin = Role::create([
'name' => 'admin',
'display_name' => 'Admin',
'description' => 'Only one and only admin',
]);
//create a permission for role
$manage_users = Permission::create([
'name' => 'manage-users-roles-and-permissions',
'display_name' => 'Manage Users,Roles and Permissions',
'description' => 'Can manage users,roles and permission"s',
]);
//here attaching permission for admin role
$admin->attachPermission($manage_users);
//here attaching role for user
$veeru->attachRole($admin);
//here iam creating another role and permisssion
$application = Role::create([
'name' => 'appapirequestlogs',
'display_name' => 'AppApiRequestLogs',
'description' => 'This has full control on Application Core Request logs',
]);
$corereq = Permission::create([
'name' => 'appapireqlogindex',
'display_name' => 'AppApiReqLogIndex',
'description' => 'This has control on Application Core Request Logs index only',
]);
here attaching roles and permissions
$application->attachPermission($corereq);
$veeru->attachRole($application);
}
After seeding that create a routes file and controller for roles and permissions
routes.php
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix' => 'admin'], function () {
Route::controller('roles', 'RolesController');
Route::controller('permissions', 'PermissionsController');
Route::controller('users', 'UsersController');
});
});
RolesController.php
use App\Permission;
use App\Role;
use Illuminate\Http\Request;
use App\Http\Requests;
class RolesController extends Controller
{
function __construct()
{
$this->middleware('auth');
$this->middleware('role:admin');
$this->middleware('permission:manage-users-roles-and-permissions');
}
public function getIndex(Request $request)
{
$roles = Role::with('perms')->get();
return view('roles.index', ['roles' => $roles]);
}
public function getCreate()
{
return view('roles.create');
}
public function postCreate(Request $request)
{
$role = Role::create([
'name' => $request->name,
'display_name' => $request->display_name,
'description' => $request->description
]);
return redirect()->to('admin/roles/index');
}
public function getUpdate($id)
{
$role = Role::findOrFail($id);
return view('roles.update', ['role' => $role]);
}
public function postUpdate(Request $request)
{
$role = Role::findOrFail($request->get('id'));
$role->name = $request->get('name');
$role->display_name = $request->get('display_name');
$role->description = $request->get('description');
$role->save();
return redirect();
}
public function getDelete($id)
{
$role = Role::findOrFail($id);
$role->delete();
return redirect();
}
public function getAttach(Request $request)
{
$role = Role::where('id', '=', $request->id)->with('perms')->first();
$permissions_id = $role->perms->pluck('id')->toArray();
$permissionsNotAttached = Permission::whereNotIn('id', $permissions_id)->get();
return view('roles.attach', compact('role', 'permissionsNotAttached'));
}
public function postAttach(Request $request)
{
$role = Role::findOrFail($request->id);
$permission = Permission::findOrFail($request->permission);
$role->attachPermission($permission);
return redirect();
}
public function getDetach(Request $request)
{
$role = Role::findOrFail($request->role_id);
$permission = Permission::findOrFail($request->permission_id);
$role->detachPermission($permission);
return redirect()->to('/admin/roles/index');
}
}
Similarly create PermissionsController.php
use App\Http\Requests\PermissionRequest;
use App\Permission;
use App\Http\Requests;
class PermissionsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('role:admin');
$this->middleware('permission:manage-users-roles-and-permissions');
}
public function getIndex()
{
$permissions = Permission::all();
return view('permissions.index', ['permissions' => $permissions]);
}
public function getCreate()
{
return view('permissions.create');
}
public function postCreate(Request $request)
{
$permission = Permission::create([
'name' => $request->name,
'display_name' => $request->display_name,
'description' => $request->description
]);
return redirect();
}
public function getUpdate($id)
{
$permission = Permission::findOrFail($id);
return view('permissions.update', ['permission' => $permission]);
}
public function postUpdate(Request $request)
{
$permission = Permission::findOrFail($request->get('id'));
$permission->name = $request->get('name');
$permission->display_name = $request->get('display_name');
$permission->description = $request->get('description');
$permission->save();
return redirect();
}
public function getDelete($id)
{
$permission = Permission::findOrFail($id);
$permission->delete();
return redirect();
}
}
After Creating first given process
create roles middleware example CheckRole
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param $role
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
if (\Auth::user()->hasRole($role)) {
return $next($request);
} else {
return response()->view('errors.401');
}
}
}
now create Check Permission
<?php namespace App\Http\Middleware;
use Closure;
class CheckPermission
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param $permission
* #return mixed
*/
public function handle($request, Closure $next, $permission)
{
if (\Auth::user()->can($permission)) {
return $next($request);
} else {
return response()->view('errors.401');
}
}
}
add these middlewares in kernal.php
'role' => CheckRole::class,
'permission' => CheckPermission::class
Now create a role with a name and add permissions to it.
example:
1.create a role name festivals.
2.now create multiple permissions for that
->fesindex (only forr index viewing)
->fesedit (only for edit and update)
->fesadd (only for adding)
->fesdelete (only for deleting)
3.now attach which permissions you want to give to that role festivals
4.if you want a user to see only index page then
for role festivals attach only fesindex
5.if you want a user to see index and add a new festival then create a new role for him and add fesindex and fes add
Now created permissions are placed in your controller
function __construct(FestivalRepository $repo)
{
$this->middleware('auth');
$this->middleware('permission:fesindex', ['only' => 'getFestivals']);
$this->middleware('permission:fesedit', ['only' => ['getFestival', 'postUpdateFestival']]);
$this->middleware('permission:fesadd', ['only' => ['getAddFestival', 'postAddFestival']]);
$this->middleware('permission:fesapprove', ['only' => 'getChangeStatus']);
$this->middleware('permission:fesdelete', ['only' => 'getDeleteFestival']);
}
here getFestivals,getAddFestival etc are methods in controller.
In my application, a user has the ability to remind another user about an event invitation. To do that, I need to pass both the IDs of the event, and of the user to be invited.
In my route file, I have:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
In my view, I have:
{!!link_to_route('remindHelper', 'Remind User', $parameters = array($eventid = $event->id, $userid = $invitee->id) )!!}
In my controller, I have:
public function remindHelper($eventid, $userid)
{
$event = Events::findOrFail($eventid);
$user = User::findOrFail($userid);
$invitees = $this->user->friendsOfMine;
$invited = $event->helpers;
$groups = $this->user->groupOwner()->get();
return view('events.invite_groups', compact('event', 'invitees', 'invited', 'groups'));
}
However, when I hit that route, I receive the following error:
Missing argument 2 for App\Http\Controllers\EventsController::remindHelper()
I'm sure I have a formatting error in my view, but I've been unable to diagnose it. Is there a more efficient way to pass multiple arguments to a controller?
When you define this route:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
You are saying that a single URI argument will be passed to the method.
Try passing the two arguments, like:
Route::get('events/{event}/remind/{user}', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
View:
route('remindHelper',['event'=>$eventId,'user'=>$userId]);
Route :
Route::get('warden/building/{buildingId}/employee/{employeeId}',[
'uses'=>'WardenController#deleteWarden',
'as'=>'delete-warden'
]);
View :
Controller:
public function deleteWarden($buildingId,$employeeId){
$building = Building::find($buildingId);
$building->employees()->detach($employeeId);
return redirect('warden/assign/'.$buildingId)->with('message','Warden Detached successfully');
}
This is how you do it:
Click Here
Go to your controller and write code like following:
public function passData()
{
$comboCoder=['Bappy','Sanjid','Rana','Tuhin'];
$ffi=['Faisal','Sanjid','Babul','Quiyum','Tusar','Fahim'];
$classRoom=['Sanjid','Tamanna','Liza'];
return view('hyper.passData',compact('comboCoder','ffi','classRoom'));
}
/*
Again, in View part use:
(passData.blade.php)
*/
<u>Combocoder:</u>
#foreach($comboCoder as $c)
{{$c}}<br>
#endforeach
<u>FFI</u>
#foreach($ffi as $f)
{{$f}}<br>
#endforeach
<u>Class Room </u>
#foreach($classRoom as $cr)
{{$cr}}<br>
#endforeach
Route::get('/details/{id}/{id1}/{id2}', 'HomeController#SearchDetails');
//pass data like the below code
<a href="{{url("/details/{$orga_list->dcode}/{$orga_list->dname}/{$GroupHead}")}}"
target="_blank" > Details </a>
//controller write like the below code
public function SearchDetails($id, $searchtext,$grp_searchtext)
{
// get data like the below code
$data['searchtext'] = $searchtext;
$data['grp_searchtext'] = $grp_searchtext;
$data['id_is'] = $id;
}
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('author/{author_name}/book/{title}', 'show')
->name('book.show');
});
Now update the controller like:
app/Http/Controllers/BookController.php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Author;
use Illuminate\Http\Request;
class BookController extends Controller
{
public function show(Request $request, Author $author, Book $book)
{
return view('show',[
'book' => $book->show($request)
]);
}
}
Now update the book model:
app\Models\Book.php
namespace App\Models;
use App\Common\HasPdf;
use App\Common\HasImage;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Book extends Model
{
use HasFactory;
protected $guarded = [];
public function author() : BelongsTo
{
return $this->belongsTo(Author::class);
}
public function url()
{
return URL::route('book.show', [
'author_name' => $this->author->author_name,
'title' => $this->title,
]);
}
}
<h3>{{ $item->title }}</h3>
Hope it can help you.
I'm new to Laravel 5.
I have a route post /subscribe.
//Subcribe
Route::post('/subscribe','SubscribeController#postSubscribe');
When I goto it, my Laravel application auto redirecting me to : /auth/login
I notice, in my
I have : /app/Http/routes.php
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Auth Controller
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
}
PasswordController
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller {
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\PasswordBroker $passwords
* #return void
*/
public function __construct(Guard $auth, PasswordBroker $passwords)
{
$this->auth = $auth;
$this->passwords = $passwords;
$this->middleware('guest');
}
}
Request by #SW
SubscribeController
<?php
namespace App\Http\Controllers;
use App\Subscribe;
use Input, Validator, Auth, Redirect, Request, Session, Mail, View;
class SubscribeController extends Controller {
public function index()
{
$subscribes = Subscribe::all();
return View::make('subscribes.index')
->with('subscribes',$subscribes);
}
//------------------------------------------------------------------------------------------------- [ Create]
public function create()
{
return View::make('subscribes.create');
}
//------------------------------------------------------------------------------------------------- [ Store ]
public function store()
{
$validator = Subscribe::validator(Input::all());
if ($validator->fails()) {
return Redirect::to('subscribe/create')
->withErrors($validator)->withInput();
} else {
$subscribe = new Subscribe;
$subscribe->email = Input::get('email');
$subscribe->save();
return Redirect::to('/subscribe')
->with('success','The web directory was created succesfully!');
}
}
//------------------------------------------------------------------------------------------------- [ Show ]
public function show($id)
{
$subscribe = Subscribe::findOrFail($id);
return View::make('subscribes.show')
->with('subscribe', $subscribe);
}
//------------------------------------------------------------------------------------------------- [ Edit ]
public function edit($id)
{
$subscribe = Subscribe::findOrFail($id);
return View::make('subscribes.edit')
->with('subscribe', $subscribe );
}
//------------------------------------------------------------------------------------------------- [ Update ]
public function update($id)
{
$validation = Subscribe::validator(Input::all());
if ($validation->fails()) {
return Redirect::to('subscribe/'. $id . '/edit')->withErrors($validation);
} else {
$subscribe = Subscribe::findOrFail($id);
$subscribe->email = Input::get('email');
$subscribe->save();
return Redirect::to('subscribe')
->with('success','The web directory was updated succesfully!');
}
}
//------------------------------------------------------------------------------------------------- [ Destroy ]
public function destroy($id){
$subscribe = Subscribe::find($id);
$subscribe->delete();
return Redirect::to('subscribe')
->with('success','The web directory was deleted succesfully!');
}
public function postSubscribe() {
$subscribe_email = Input::only('subscribe_email');
// Validation
$validator = Validator::make( $subscribe_email ,
array(
'subscribe_email' => 'email|unique:subscribes,email',
)
);
if ($validator->fails()) {
return Redirect::to('/#footer')
->with('subscribe_error', $subscribe_email['subscribe_email']. ' is already an Aveniros subscriber.')
->withErrors($validator)->withInput();
}else{
$subscribe = new Subscribe;
$subscribe->email = Input::get('subscribe_email');
$subscribe->save();
return Redirect::to('/thank-you');
}
}
public function postSubscribeAjax() {
$data = Request::all();
//dd($data); Stuck HERE
// Validation
$validator = Validator::make( $data,
array(
'subscribe_email' => 'email|unique:subscribes,email',
)
);
if ($validator->fails()) {
return Redirect::to('/#footer')
->with('subscribe_error','This email is already subscribed to us.')
->withErrors($validator)->withInput();
}else{
$subscribe = new Subscribe;
$subscribe->email = Input::get('subscribe_email');
$subscribe->save();
return Redirect::to('/thank-you');
}
}
public function thankyou() {
return view('subscribes.thankyou');
}
}
Why is that ? and how do I fix it ? Is this even a normal behavior ?
You need to have a method for your each of your routes, telling Laravel how to treat each route. For example in your route file, there should be Route::get('index#SubscribeController); line. As Staurt Wagner has mentioned, if you just navigate to a path, you are sending get request to the server.
If you are using Laravel 5, your controllers should be in the \app\Http\Controllers path.
Your index method in theSubscribeController can simply be:
public function index(){
return "Hello World!";
}
For a much thorough tutorial, refer to this wonderful series on Laracast.