I want to learn how csrf works. Then, I found the following website.
The teaching provided in it is: Add a function to modify the user's name for the laravel dashboard. And this teaching is in the chapter "Set Up Simulated Functionality".
https://www.stackhawk.com/blog/laravel-csrf-protection-guide/
Create a new controller /app/Http/Controllers/UserController.php
<?php
namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesSession;
class UserController extends Controller
{
public function update(Request $request)
{
$user = User::findOrFail(auth()->user()->id);
$user->name = $request->name;
$user->save();
Session::flash('message', 'Name updated!');
return back();
}
}
update /resources/views/dashboard.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
You're logged in!
</div>
{{-- This is the new code block to be added to the file --}}
#if(Session::has('message'))
<div class="bg-green-100 border-t-4 border-green-500 px-4 py-3">
<p class="text-sm">{{ Session::get('message') }}</p>
</div>
#endif
<div class="p-6 bg-white border-b border-gray-200">
<form method="POST" action="/users/">
#method('PATCH')
<div class="mt-4 max-w-xs">
<x-input value="{{ auth()->user()->name }}" id="name" class="block mt-1 w-full" type="text" name="name" placeholder="Your name here" required />
</div>
<x-button class="mt-3">
{{ __('Update Name') }}
</x-button>
</form>
</div>
{{-- End of the new code block --}}
</div>
</div>
</div>
</x-app-layout>
update routes/web.php
//add this to the top of the file
use AppHttpControllersUserController;
//This goes with the other routes
Route::patch('/users/', [UserController::class, 'update'])->middleware(['auth']);
After I added/modified the following three files according to his teaching...I got such an error message :
InvalidArgumentException
Unable to locate a class or view for component [input].
public/ index.php : 52 require_once
.
.
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = $kernel->handle(
$request = Request::capture() // error
)->send();
$kernel->terminate($request, $response);
.
.
In my understanding, the code written by this master is not wrong. In addition, this is a container that uses docker to run, I don't think it should be a version problem.
What is the reason for this error? Please how can I fix this error?
The error is in the view /resources/views/dashboard.blade.php,
you don't have any components called <x-input and <x-button,
just raplace it with normal html input and button, or create missing blade component
https://laravel.com/docs/9.x/blade#components
Related
i am new to Laravel so am trying to delete and edit some posts which is linked to a page where the update from is located but each time i update or delete, i get a 404 error or the page is not found(i think the problem is the url).
here is my code for the update
public function update(Request $request, $id) {
$car = Car::where('id', $id)
->update([
'name'=> $request->input('name'),
'founded'=> $request->input('founded'),
'description' => $request->input('description')
]);
return redirect('/cars'); }
this one is for delete/destroy
public function destroy($id)
{
$car = Car::find($id);
$car->delete();
return redirect('/cars');
}
i also have an edit.blade.php
#section('content')
<div class="m-auto w-4/8 py-24">
<div class="text-center">
<h1 class="text-5xl uppercase bold">
Update Car
</h1>
</div>
</div>
<div class="flex justify-center pt-20">
<form action="../cars/{{ $car->id }}" method="POST">
#csrf
#method('PUT')
<div class="block">
<input type="text" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="name"
value="{{ $car->name }}"><br>
<input type="number" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="founded"
value="{{ $car->founded }}"><br>
<input type="text" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="description"
value="{{ $car->description }}"><br>
<button type="submit" class="bg-teal-500 block shadow-5xl mb-10 p-2 w-80 uppercase font-bold text-white">
Update
</button>
</div>
</form>
</div>
#endsection
the last part contains the buttons for delete and edit
#foreach ($cars as $car )
<div class="m-auto">
<span class="uppercase text-teal-500 font-bold text-xs italic">
Founded : {{ $car->founded }}
</span>
<h2 class="text-gray-700 text-5xl">
{{ $car->name }}
</h2>
<p class="text-lg text-gray-700 py-6">
Description : {{ $car->description }}
</p>
<div class="float-right">
<a class=" pb-2 italic text-teal-500" href="cars/{{ $car->id }}/edit">
Edit →
</a>
<form action="../cars/{{ $car->id }}" method="POST">
#csrf
#method("delete")
<button type="submit" class="pb-2 italic text-red-500">
Delete →
</button>
</form>
</div><br><br>
<hr class="mt-4 mb-8">
</div>
#endforeach
here is my route
Route::resource('/cars', CarsController::class);
first check route with this command php artisan route:list
then you see list like this
DELETE cars/{car}
PUT|PATCH cars/{car}
the car name is important to automatically Laravel find entity base on Type hint Car $car, so in controller use this convention :
public function destroy(Car $car)
{
$car->delete();
return redirect('/cars');
}
public function update(Request $request, Car $car) { ... }
You should not generate url like this: action="../cars/{{ $car->id }}"
Instead use action="{{ route('cars.update', $car->id) }}"
You can see the available routes by running this command
php artisan route:list
So, Basically when you use resource you get predefined route list by Laravel with different methods.
Example your route is
Route::resource('/cars', CarsController::class);
Then laravel generate routes like this.
To check route list run php artisan route:list
Route::GET('/cars', [CarsController::class, 'index'])->name('cars.index');
Route::GET('/cars/create', [CarsController::class, 'create'])->name('cars.create');
Route::POST('/cars', [CarsController::class, 'store'])->name('cars.store');
Route::GET('/cars/{id}', [CarsController::class, 'show'])->name('cars.show');
Route::GET('/cars/{id}/edit', [CarsController::class, 'edit'])->name('cars.edit');
Route::PUT('/cars/{id}', [CarsController::class, 'update'])->name('cars.update');
Route::DELETE('/cars/{id}', [CarsController::class, 'destroy'])->name('cars.destroy');
Then you can use in form with defined methods.
Example to use
{{ route('cars.destroy', ['id' => $car->id]) }}
Source Laravel documentation: click to check more resource method on offical Laravel website.
I am getting below shown error in Laravel website. The goal over here is to display the product. I have also shared the image of the error on this issue log. Kindly check and let me know where the issue is as I am not able to figure out.
I am running the laravel project locally. Any suggestion or help from the Laravel community is welcomed. Please help so that I can proceed further.
ErrorException
Trying to get property 'title' of non-object (View: C:\DK\Practice\Laravel\example-app\resources\views\product.blade.php)
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\DK\Practice\Laravel\example-app\resources\views/product.blade.php:9
<x-base-layout>
<div class="flex m-4">
<div class="w-1/2 rounded shadow overflow-hidden">
{{-- <img class="object-cover w-full" src="{{asset($product->image_url)}}"/> --}}
</div>
<div class="w-1/2 rounded bg-white ml-2 p-4 shadow relative">
<div class="font-semibold">{{$product->title}}</div>
<div class="text-sm text-gray-500">{{$product->short_desc}}</div>
<div class="text-xs text-gray-500 mt-2">{{$product->long_desc}}</div>
{{-- Seller info --}}
<div class="mt-4">
<div class="text-xs font-semibold text-gray">Sold by</div>
<div class="text-sm text-gray-500">{{$product->user->name}}</div>
</div>
1 - product.blade.php
<x-base-layout>
<div class="flex m-4">
<div class="w-1/2 rounded shadow overflow-hidden">
{{-- <img class="object-cover w-full" src="{{asset($product->image_url)}}"/> --}}
</div>
<div class="w-1/2 rounded bg-white ml-2 p-4 shadow relative">
<div class="font-semibold">{{$product->title}}</div>
<div class="text-sm text-gray-500">{{$product->short_desc}}</div>
<div class="text-xs text-gray-500 mt-2">{{$product->long_desc}}</div>
{{-- Seller info --}}
<div class="mt-4">
<div class="text-xs font-semibold text-gray">Sold by</div>
<div class="text-sm text-gray-500">{{$product->user->name}}</div>
</div>
<div class="mt-2">
<div class="text-xs font-semibold text-gray">Phone number</div>
#auth
<div class="text-sm text-gray-500">{{$product->user->phone}}</div>
#else
<div class="text-sm text-gray-500">********** Login to view</div>
#endauth
</div>
<div class="mt-2">
<div class="text-xs font-semibold text-gray">Email address</div>
#auth
<div class="text-sm text-gray-500">{{$product->user->email}}</div>
#else
<div class="text-sm text-gray-500">********** Login to view</div>
#endauth
</div>
{{-- Product price --}}
<div class="absolute bottom-0 right-0 m-6 rounded-full px-4 py-2 bg-green-500">
<div class="text-white font-fold text-sm">Rs. {{$product->price}}/-</div>
</div>
</div>
</div>
</x-base-layout>
2 - ProductsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\Auth;
class ProductsController extends Controller
{
//fetch all products
public function index() {
$products=Product::all();
return view('products')->with('products',$products);
}
//Fetch a product by id
public function show($id){
$product=Product::find($id);
return view('product')->with('product',$product);
dd($product);
}
3 - Route - web.php
<?php
use App\Http\Controllers\ProductsController;
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('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Route::get('/',[ProductsController::class,'index']
);
Route::get('/product/{id}',[ProductsController::class,'show']);
Error screenshot:
I think, you have a little prob in your show() method. What happen if the find method return a null? You will exactly get what you are getting, trying to access a property on null object.
Change you code as bellow, and then you'll get a 404 Not found.
//Fetch a product by id
public function show($id){
$product=Product::findOrFail($id);
return view('product')->with('product',$product);
dd($product); // This will never be executed.
}
I am a beginner on Laravel and I am trying to improve.
I am trying to create a blog with 3 differents Roles.
I have a problem displaying my user's dashboard when registered. Apparently the users() method does not exist but it does exist in my role model.
screen of the error
database screen
role model
public function users(){
return $this->belongsToMany(User::class);
}
User Model
public function role(){
return $this->belongsTo(Role::class);
}
dashboard.blade.php
#if(Auth::users()->role->libelle =='admin');
#include('roles.admin')
#elsif(Auth::users()->role->libelle =='trainer');
#include('roles.trainer')
#elsif(Auth::users()->role->libelle =='user');
#include('roles.user')
#endif
user.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
You're logged in as user!
</div>
</div>
</div>
</div>
</x-app-layout>
I'm am trying to get data from a database table and passing it to the modal but it is saying the array I am passing in undefined. Here is my Controller:
public function displayLocNotesForModal() {
$notesLoc = Note::all();
return view('/components/callCenter/modalLocNotes', ['notesLoc' => $notesLoc]);
}
Here is my Route:
Route::get('/components/callCenter/modalLocNotes', 'App\Http\Controllers\CallCenter\NoteController#displayLocNotesForModal');
Here is my modal:
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-headline">
Location #{{ $title }} Notes
</h3>
<div class="mt-2">
<p class="text-sm leading-5 text-gray-500">
{{-- {{ $slot }} --}}
#foreach($notesLoc as $notes)
#if($notes == $title)
works
#endif
#endforeach
</p>
</div>
</div>
I think it should be like below, assuming the components folder is in your resources/views folder
return view('components.callCenter.modalLocNotes', ['notesLoc' => $notesLoc]);
Also providing a link to docs Laravel nested view directories
fast and (hopefully) simple question. I am starting out with a project. I'm using de standard authorisation that comes with laravel. Registering a user works fine and it is logged in afterwards. I can also logout with no problem. The login screen seems fine. But when I enter my login credentials and click on 'login' nothing happens. no redirects or errors at all. It doesnt matter if I enter right, wrong or nothing at all in the login fields.
Login controller (Should be default):
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/profile';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Login view (should also be default):
#extends('layouts.app')
#section('content')
<div class="container mx-auto">
<div class="w-full max-w-xs mx-auto px-4">
<h1 class="mb-4 text-center">Inloggen</h1>
<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="mb-4">
<label class="block text-grey-darker text-sm font-bold mb-2" for="username">
E-mailadres
</label>
<input id="email" type="email" class="shadow appearance-none border rounded w-full py-2 px-3 text-grey-darker {{ $errors->has('email') ? 'border-red-dark' : 'border-grey-light' }}" name="email" value="{{ old('email') }}" required autofocus>
{!! $errors->first('email', '<p class="text-red text-xs italic">:message</p>') !!}
</div>
<div class="mb-6">
<label class="block text-grey-darker text-sm font-bold mb-2" for="password">
Wachtwoord
</label>
<input id="password" type="password" class="shadow appearance-none border rounded w-full py-2 px-3 text-grey-darker {{ $errors->has('email') ? 'border-red-dark' : 'border-grey-light' }}" name="password" required>
{!! $errors->first('password', '<p class="text-red text-xs italic">:message</p>') !!}
</div>
<div class="flex items-center justify-between">
<button class="bg-blue hover:bg-blue-dark text-white py-2 px-4 rounded" type="button">
Inloggen
</button>
<a class="inline-block align-baseline text-xs text-grey hover:text-grey-dark" href="{{ route('password.request') }}">
Wachtwoord vergeten?
</a>
</div>
</form>
<p class="text-center text-grey text-xs">
©{{ date('Y') }} {{ config('app.name') }}. Alle rechten voorbehouden.
</p>
</div>
</div>
#endsection
It seems like your Inloggen button is the part that is wrong. Should be something like:
<button class="bg-blue hover:bg-blue-dark text-white py-2 px-4 rounded" type="submit">
Inloggen
</button>
It needs to be type="submit" to submit form data.