QueryException in Connection.php line 647: - laravel

I'm trying to save checkboxes. I should be able to select one or mutliple.
At the moment I'm getting this error
QueryException in Connection.php line 647: Array to string conversion (SQL: insert into seo (url, meta_title, meta_description, keywords, robot, updated_at, created_at) values (ff, ff, ff, ff, noindex, 2017-03-27 08:59:54, 2017-03-27 08:59:54))
Here is my create.blade.php
<div class="robots">
{!! Form::label('noindex', 'noindex') !!}
{!! Form::checkbox('robot[]', 'noindex') !!}
{!! Form::label('follow', 'follow') !!}
{!! Form::checkbox('robot[]', 'follow') !!}
</div>
my method in my seo controller
public function create()
{
//Gets all the seo that are in the database
$seos = Seo::with('menu')->get();
//Lists the title of the seo
$menu_options = Menu::pluck('title', 'id');
return view('seo::admin.create', compact('seos'))->with('menu_options', $menu_options);
}
public function store()
{
//Gets all the input in the fields in the form
$input = Input::all();
//Checks the input fields against the validation rules in the Seo model
$validation = Validator::make($input, Seo::$rules);
//If the validation fails the a message will pop up saying that there was validation errors
if($validation->fails()){
return redirect()->route('seo.create')
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors');
}
//If the validation passes then it gets saved to the database
if($validation->passes()){
$seos = new Seo();
//Gets the menu_id
$menuId = (array) array_get($input, 'menu_id');
//Saves the input to the database
$seos->fill($input)->save();
//Syncs the menu function in the Seo model to save the menu ID in menu_seo
$seos->menu()->sync($menuId);
$seos = Seo::all();
return view('seo::admin.index', compact('seos'));
}
}

You've trying to save robot array as string. You need to serialize it first. You can do it manually:
$robot = json_encode($input['robot']);
Or you can use array casting feature:
protected $casts = [
'robot' => 'array',
];
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

Related

Laravel phpunit testing controller which returns view with data

Am trying to adapt TDD on laravel, but am getting trouble to test controller which queries a collection of records and returns view with data when I run my test it returns an error message that trying to get the id of undefined property
// my test
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class JobApplicationTest extends TestCase
{
use WithoutMiddleware;
/** #test */
public function user_can_see_all_open_positions()
{
// when user visit apply for a job page
$this->withoutExceptionHandling();
$response = $this->get(route('positions.open'));
$response->assertSuccessful();
$response->assertViewIs('positions.open.index');
$response->assertViewHas('positions');
}
}
// My controller
public function open(Request $request)
{
//TODO support additional filters & searches
//initialize query
$query = Position::query()->which()->are()->open();
//paginate query result
$positions = $query->paginate(config('app.defaults.pageSize'));
$data = [
'route_title' => 'Open Job Positions',
'route_description' => 'Available Job Positions',
'positions' => $positions,
];
return view('positions.open.index', $data);
}
so the problem is when I run text it looks view is returned with no data while view references data returned to the controller
error message when running test
1) Tests\Unit\JobApplicationTest::user_can_see_all_open_positions
ErrorException: Trying to get property 'id' of non-object (View:
/var/www/html/ipf-projects/niajiri/resources/views/pos
itions/open/index.blade.php)
<h3>
<a href="{{ route('positions.preview', [
'id' => $position->id,
'slug' => str_slug($position->title)
]) }}" class="text-navy">
{!! $position->title !!} - {!! $position->organization->name !!}
</a>
</h3>
Within 'positions.open.index' it is trying to access an id property on a non-object.
This could be because your $query does not return any Position objects (i.e. $data->positions returns an empty Collection)
When running unit tests it is likely that it is creating a temporary database (sqlite by default) which will not be populated with any data. Try adding some Positions in your test like so:
/** #test */
public function user_can_see_all_open_positions()
{
// Create Positions
Position::create([/* Some data here */]);
Position::create([/* Some data here */]);
// when user visit apply for a job page
$this->withoutExceptionHandling();
$response = $this->get(route('positions.open'));
$response->assertSuccessful();
$response->assertViewIs('positions.open.index');
$response->assertViewHas('positions');
}

Why is blade displaying the model original value and not attribute?

In my controller I am mutating the original value of a model like this;
$tags = [
'[firstName]',
'[city]'
];
$values = [
$recipient['firstName'],
$city['name']
];
$module['content'] = str_replace($tags, $values, $module['content']);
Then in blade I am just trying to use the mutated attribute;
{!! $module['content'] !!}
I can see that my mutation is working when I dd the model but once passed to my view, it is presenting the original value and not the attribute.
Why/how is this?
Thanks

How to clear form input after save?

How can I clear form input on form submit?
After URL is saved I return the view for creating a form so I can add new URL.
The problem is that this time URL is populated from previous save.
How can I empty it after save?
Isn't that the point of second parameter which is set to null?
Using laravel version 5.4.36.
In the "create" iew I have a form with URL input:
{!! Form::open(['route' => 'urls.store']) !!}
{{ Form::url('url', null, array('class' => 'form-control')) }}
{{ Form::submit('Add domain', array('class' => 'btn' )) }}
Store method saves URL to database and returns the same view:
public function store(Request $request)
{
// URL Validation
$this->validate($request, array(
'url' => 'required|url|unique:urls'
));
// Save
$url = new Url;
$url->url = $request->url;
$url->save()
return view('urls.create');
}
Your form view should be handled by a get request on Route and submitting form is a post request .So after submitting the form you should redirect the same page not just returning the view . Check the web.php is the Routes are ok or not . Try to
add it to the store method ,I think it may help you
return redirect()->back();
or with flash message
return redirect('urls.create')->with('success', 'URL has been added');
you can make value = some values come from the controller with empty values when it's the parameters is set i.e use isset function
or
you can make a flag in the view when it sends to controller check it if it is true means you submit the form, in this case, make the values with empty

Trying to get property 'amount' of non-object in view sev.blade.php

below is my PaymentController
public function handleGatewayCallback(Request $request){
$paymentDetails = Paystack::getPaymentData();
return view('sev', ['details' => $paymentDetails]);
now in my view page, I simply loop:
#foreach($details as $detail) {{detail->amount}} #endforeach.
but I get the error: trying to get property of 'amount' of non object in my view. please how do I get all the json data contained in $paymentDetails and save it to my database.

How to use a Form::Select with a Pivot Table in Laravel 5.6

I try to use Form::select in Laravel 5.6, but when I went to the Edit Page, in the select, there are options with all the data of the object Model instead of a regular field.
I have a Game Model with a relationship ManyToMany with a Tag Model.
In my edit function from the Game Controller
public function edit($item)
{
$tags = Tag::all();
return view('megadmin.games.edit', compact('item', 'tags'));
}
In my Form Blade :
{!! Form::select('tags', $tags, array_pluck($tags, 'id_tag','name'), ['class' => 'form-control'])!!}
Here the result :
The result
I just want a normal select/options with the data AND i want to retrieve the model Tag associated with the Game in the Game Form.
Thanks you for your help ^^
I assume you are using Form model binding, so you can do this:
In your Game model create a new method only for you Form Model Binding:
class Game extends Model
{
use FormAccessible;
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function formTagsAttribute()
{
return $this->tags()->pluck('id_tag');
}
}
In your Controller:
public function edit($item)
{
$tags = Tag::pluck('name', 'id_tag');
return view('megadmin.games.edit', compact('item', 'tags'));
}
In your view:
{!! Form::model($game, [$attributes]) !!}
{!! Form::select('tags', $tags, null, ['class' => 'form-control']) !!}
.
.
.
{!! Form::close() !!}
Controller
public function edit($item)
{
$tags = Tag::all();
$goodTag = $item->tags()->first()->id;
//here assuming `$item` is your Game object and
//you have ManyToMany relation with tags with `tags` function in game model
//lots of assuming
return view('megadmin.games.edit', compact('item', 'tags', 'goodTag));
}
View
{!! Form::select('tags', array_pluck($tags,'name', 'id_tag'), $goodTag, ['class' => 'form-control'])!!}
Here is the laravel form select source code https://github.com/illuminate/html/blob/master/FormBuilder.php#L393
and array_pluck https://laravel.com/docs/5.6/helpers#method-array-pluck

Resources